<?php
/**
 * Created by PhpStorm.
 * User: xianxuefeng
 * Date: 2018/5/24
 * Time: 14:07
 */
namespace app\controllers\marketing;
use app\models\marketing\MailGroup;
use app\models\marketing\Category;
use app\models\marketing\UserGroup;
use app\models\crontab\CrmPush\UserLabelQueue;
use Yii;
class AnalysisMailGroupController  extends \app\base\Controller
{

    private $openDiviceName= [
        '0' =>'other',
        '1' => 'ios',
        '2' => 'android',
        '3' => 'pc',
        '4' => 'pad',
        '5' => 'wap'
    ];
    private $singleDeviceName =
        [
            '0' =>'other',
            '1' => 'ios',
            '2' => 'android',
            '3' => 'pc',
            '4' => 'pad',
            '5' => 'wap'
        ];
    private $mongodsn;
    private $mongo;
    private $prefix = 'funnel_analysis_group_id_';
    private $res_backup = 'funnel_analysis_response_back';   //数据分析响应备份
    /**
     * 初始化
     */
    public function init()
    {
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。
        $this->mongodsn  =  yii::$app->mongodb->dsn;
        $replicaSet = isset(yii::$app->mongodb->replicaSet) ? yii::$app->mongodb->replicaSet:null;

        if (! empty($this->mongodsn)) {
            if (! empty($replicaSet)) {
                $m=  new \MongoClient($this->mongodsn,array("replicaSet" => $replicaSet));
            }else {
                $m=  new \MongoClient($this->mongodsn);
            }
            $databaseName = trim(strrchr($this->mongodsn,"/"),"/");   //获取配置信息中，/后面的库名
            $this->mongo = $m->$databaseName;
            if (empty($this->mongo)) {
                exit(json_encode(['status' => 0,'msg' => 'mongodb 连接失败，请稍候再试','data' => []]));
            }
        } else {
            exit(json_encode(['status' => 0,'msg' => 'mongodb 连接失败，请稍候再试','data' => []]));
        }
    }
    private function error($msg = '系统繁忙') {
        if (empty($msg)) {
            $msg = '系统繁忙';
        }
        exit(json_encode(['status' => 0,'msg' => $msg,'data' => []]));
    }
    private function success($data = [],$msg = '成功') {
        exit(json_encode(['status' => 1,'msg' => $msg,'data' =>$data]));
    }

    public function actionTotalTransformation() {
        $method = yii::$app->request->getMethod();
        $group_id = yii::$app->request->$method("group_id");
        yii::$app->request->$method("site");
        if (empty($group_id)) {
            $this->error('group_id 不能为空');
        }
        $res = self::totalTransformation(['group_id' => $group_id]
        );
        $this->success($res);
    }

    private function getmailGroupSendCount($group_id) {
        $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,have_send_test,track_code from mail_group where group_id = $group_id";
        $mailGroupList = yii::$app->db->createCommand($sql)->queryAll();
        if (empty($mailGroupList)) {
            return 0;
        }
        return $mailGroupList[0]['send_ok_count'];
    }
    /**
     *
     * 订单转化
     * 订单总额
     * 付款总额
     * 订单数
     * 付款订单数
     * 付款金额率
     * 付款订单率
     *
     */
    public  function totalTransformation($info)
    {  // $post['group_id'] = 15571;
//        $post = Yii::$app->request->post();
        if (empty($info['group_id'])) {
           return false;
        }
        $group_id = $info['group_id'];
        $totalTrans= [                 // 邮件转化分析
            'order_amount' => 0,                // 订单总额
            'pay_order_amount' => 0,            // 付款总额 ,note :汇总统计该发送分组的已支付订单总金额, 币种为美元（$）。
            'order_num' => 0,                   // 订单数,note : 汇总统计该发送分组的所有订单数（单位：个），按订单号汇总
            'pay_order_num' => 0,               // 付款订单数 ,note : 汇总统计该发送分组的所有已支付订单数（单位：个），按订单号汇总。
            'pay_amount_rate' => 0,             // 付款金额率 ,note : 付款金额率=[付款总额/订单总额]*100%
            'pay_order_rate' => 0,              // 付款订单率 ,note : 付款订单率=[付款订单数/订单数] *100%
            'send_email_num' => 0,           // 邮件发送数量
            'send_email_success_num' => 0,   // 邮件发送成功的数量, note : 渠道返回的该发送分组发送成功用户数。
            'email_success_rate' => 0,          // 邮件发送成功率 , note :  渠道返回的该发送分组发送成功用户数。
            'email_open_num' => 0,           // 邮件打开的数量 , note : 取该发送分组的独立打开用户数
            'email_open_rate' => 0,             // 邮件打开率 , note : 打开率=[独立打开用户数/发送成功] *100%
            'user_click_num' => 0,           // 用户点击邮件数量（用户点击）, note : 取该发送分组的独立点击用户数
            'user_click_rate' => 0,             // 用户点击邮件率（用户点击率）, note : 点击转化率=[独立点击用户数/独立打开用户数] *100%
            'single_user_num' => 0,     // 下单用户数 (汇总统计该发送分组的下单用户数（按网站用户ID汇总）)
            'single_user_rate' => 0,    // 下单用户率 (用户下单率=[下单用户数/独立点击用户数] *100%)
            'pay_user_num' => 0,        // 付费用户数(用户付款) ,note :汇总统计该发送分组的下过订单并且已支付的用户数（按网站用户ID汇总）
            'pay_user_rate' => 0,       // 付费用户率 note : 用户付款率=[用户付款 /用户下单] *100%
            'bounces_num' => 0,         // 弹回数 note: 弹回总数=硬弹用户数+软弹用户数
            'bounces_rate' => 0,        // 弹回率 note: 弹回率=[弹回总数/发送总量]*100%
            'hard_bounces_num' => 0,    // 硬弹数
            'hard_bounces_rate' => 0,   // 硬弹率 note: 硬弹率=[硬弹用户数/弹回总数]*100%
            'soft_bounces_num' => 0,    // 软弹数
            'soft_bounces_rate' => 0,   // 软弹率 note: 软弹率=[硬弹用户数/弹回总数]*100%
            'complaint_num' => 0,       // 投诉数
            'complaint_rate' => 0,      // 投诉率 note: 投诉率=[投诉用户数/发送成功数] *100%
            'unsubscribe_num' => 0,     // 退订数
            'unsubscribe_rate' => 0,    // 退订率 note: 投诉率=[投诉用户数/发送成功数] *100%
            'mailbox_unsubscribe_num' =>0, // 邮箱退订数
            'mail_unsubscribe_num' => 0,   //邮件退订数
            'mailbox_unsubscribe_rate' => 0, //  邮箱退订率
            'mail_unsubscribe_rate' => 0,    // 邮件退订率
        ];

        $table = $this->prefix.$group_id;
        $db =  $this->mongo->$table;
        /*
        //订单总额和订单数
        $orderInfo = $db->aggregate([
            ['$unwind'=>'$orders'],
            ['$group' =>[
            '_id' =>"",
            'order_amount' => ['$sum' => '$orders.order_amount'],
            'order_num' => ['$sum' =>1]             //order_num(订单数)
        ]]]);

        if (! empty($orderInfo['result'])) {
            $totalTrans['order_amount'] = $orderInfo['result'][0]['order_amount'];
            $totalTrans['order_num'] = $orderInfo['result'][0]['order_num'];
        }

        //付款总额和付款订单数
        $orderInfo = $db->aggregate([
            ['$unwind'=>'$orders'],
            ['$match'=>['orders.pay_status'=>['$gte'=>"1"]]],
            ['$group'=>['_id'=>'',
                'pay_order_num' =>['$sum' =>1],
                'pay_order_amount'=>['$sum'=>'$orders.order_amount'],
            ]]
        ]);
        if (! empty($orderInfo['result'])) {
            $totalTrans['pay_order_amount'] = $orderInfo['result'][0]['pay_order_amount'];
            $totalTrans['pay_order_num'] = $orderInfo['result'][0]['pay_order_num'];
        }

        //$totalTrans['pay_user_num'] = $db->find(['pay_status'=> ['$gte'=>"1"]])->count();
        $orderInfo = $db->aggregate([
            ['$unwind'=>'$orders'],
            ['$match'=>['orders.pay_status'=>['$gte'=>"1"]]],
            ['$group'=>['_id'=>'$user_id'
            ]]
        ]);
        // 付费用户数
        if (! empty($orderInfo['result'])) {
            $totalTrans['pay_user_num'] = count($orderInfo['result']);
        }

        $orderInfo = $db->aggregate([
            ['$match'=>['orders.order_id'=>['$ne'=>null]]],
            ['$group'=>['_id'=>'$user_id']]
        ]);

        //下单用户数
        if (! empty($orderInfo['result'])) {
            $totalTrans['single_user_num'] = count($orderInfo['result']);
        }
        */
        $orderList = $db->find(["orders"=>['$exists'=>"true"]],['orders'=>1,'_id'=>0]);
        $orderList = iterator_to_array($orderList);
        $orderArr = [];
        $singleUserArr = [];
        foreach ($orderList as $val) {
            if (!is_array($val['orders'])) {
                continue;
            }
            foreach ($val['orders'] as $v) {
                if ( ! isset($orderArr[$v['order_sn']])) {
                    ++$totalTrans['order_num'];
                    $totalTrans['order_amount'] += isset($v['order_amount']) ? $v['order_amount']: 0;
                    if ($v['pay_status']>= 1) {
                        ++$totalTrans['pay_order_num'];
                        ++$totalTrans['pay_user_num'];
                        $totalTrans['pay_order_amount'] += isset($v['order_amount']) ? $v['order_amount'] : 0;
                    }
                    $orderArr[$v['order_sn']] = $v['order_sn'];
                    $singleUserArr[$v['user_id']] = $v['user_id'];
                }
            }
        }
        $totalTrans['single_user_num'] = count($singleUserArr);

        /*
        rder_num(订单数),
        pay_order_num(付款订单数),
        send_email_success_num(邮件发送成功的数量),
        email_open_num(邮件打开的数量),
        user_click_num(用户点击邮件数量)
        single_user_num(下单用户数),   note: 要统计have_order_record，
        pay_user_num(付费用户数),
        bounces_num(弹回数),
        soft_bounces_num(软弹数)
        hard_bounces_num(硬弹数),
        complaint_num(投诉数),
        unsubscribe_num(退订数)
        */
        /*
         * [
             {$unwind:'$orders'},
             {$match:{'orders.pay_status':'1'}},
             {$group:{
                      _id:null,
                      count:{$sum:1}
                    }
             }
         ]
         */

        $totalTrans['send_email_num'] = self::getmailGroupSendCount($group_id);         // 发送总量
//        $totalTrans['send_email_success_num'] = $db->find(['$or' =>[['is_hard_bounces'=>"0"],['is_soft_bounces' =>"0"]]])->count();
        $totalTrans['email_open_num'] = $db->find(['open_count'=> ['$gte'=>1]])->count();
        $totalTrans['user_click_num'] = $db->find(['is_click'=> "1"])->count();
        $totalTrans['single_user_num'] = $db->find(['have_order_record'=> "1"])->count();
        $totalTrans['soft_bounces_num'] = $db->find(['is_soft_bounces'=> "1"])->count();
        $totalTrans['hard_bounces_num'] = $db->find(['is_hard_bounces'=> "1"])->count();
        $totalTrans['complaint_num'] = $db->find(['is_complaint'=> ['$gte'=>"1"]])->count();
        $totalTrans['mail_unsubscribe_num'] = $db->find(['is_unsubscribe'=> ['$gte'=>"1"]])->count();
//        $totalTrans['mailbox_unsubscribe_num'] = $db->find(['mailbox_unsubscribe'=> ['$gte'=>1]])->count();
        $totalTrans['mailbox_unsubscribe_num'] = $db->find(['mailbox_unsubscribe'=> '1'])->count();
        $totalTrans['unsubscribe_num'] = $totalTrans['mail_unsubscribe_num'] + $totalTrans['mailbox_unsubscribe_num'];   //退订总量
        $totalTrans['send_email_success_num'] =  $totalTrans['send_email_num'] -  $totalTrans['soft_bounces_num'] - $totalTrans['hard_bounces_num'] ;
        /*
         * pay_amount_rate 付款金额率
         * pay_order_rate 付款订单率
         * email_success_rate  邮件发送成功率
         * email_open_rate  邮件打开率
         * user_click_rate 用户点击邮件率
         * single_user_rate 下单用户率
         * pay_user_rate  付费用户率
         * bounces_rate 弹回率
         * hard_bounces_rate 硬弹率
         * soft_bounces_rate 软弹率
         * complaint_rate 投诉率
         * unsubscribe_rate 退订率
         */
         if ( ! (empty($totalTrans['order_amount']) ||
             empty($totalTrans['pay_order_amount']))) {
             $totalTrans['pay_amount_rate'] = round(100 * $totalTrans['pay_order_amount'] / $totalTrans['order_amount'],2);
         }

        if ( ! (empty($totalTrans['pay_order_num']) ||
            empty($totalTrans['order_num']))) {
            $totalTrans['pay_order_rate'] = round(100 * $totalTrans['pay_order_num'] / $totalTrans['order_num'],2);
        }
        if ( ! (empty($totalTrans['send_email_success_num']) ||
            empty($totalTrans['send_email_num']))) {
            $totalTrans['email_success_rate'] = round(100 * 
                $totalTrans['send_email_success_num'] / $totalTrans['send_email_num'],2);
        }
        if ( ! (empty($totalTrans['email_open_num']) ||
            empty($totalTrans['send_email_success_num']))) {
            $totalTrans['email_open_rate'] = round(100 * $totalTrans['email_open_num'] / $totalTrans['send_email_success_num'],2);
        }

        if ( ! (empty($totalTrans['user_click_num']) ||
            empty($totalTrans['email_open_num']))) {
            $totalTrans['user_click_rate'] = round(100 * $totalTrans['user_click_num'] / $totalTrans['email_open_num'],2);
        }
        if ( ! (empty($totalTrans['single_user_num']) ||
            empty($totalTrans['user_click_num']))) {
            $totalTrans['single_user_rate'] = round(100 * $totalTrans['single_user_num'] / $totalTrans['user_click_num'],2);
        }
        if ( ! (empty($totalTrans['pay_user_num']) ||
            empty($totalTrans['single_user_num']))) {
            $totalTrans['pay_user_rate'] = round(100 * $totalTrans['pay_user_num'] / $totalTrans['single_user_num'],2);
        }

        $totalTrans['bounces_num'] =  $totalTrans['hard_bounces_num']+ $totalTrans['soft_bounces_num'];
        if ( ! (empty($totalTrans['bounces_num']) ||
            empty($totalTrans['send_email_num']))) {
            $totalTrans['bounces_rate'] = round(100 * $totalTrans['bounces_num'] / $totalTrans['send_email_num'],2);
        }

        if ( ! (empty($totalTrans['hard_bounces_num']) ||
            empty($totalTrans['bounces_num']))) {
            $totalTrans['hard_bounces_rate'] = round(100 * $totalTrans['hard_bounces_num'] / $totalTrans['bounces_num'],2);
        }

        if ( ! (empty($totalTrans['soft_bounces_num']) ||
            empty($totalTrans['bounces_num']))) {
            $totalTrans['soft_bounces_rate'] = round (100 * $totalTrans['soft_bounces_num'] / $totalTrans['bounces_num'],2);
        }
        if ( ! (empty($totalTrans['complaint_num']) ||
            empty($totalTrans['send_email_success_num']))) {
            $totalTrans['complaint_rate'] = round (100 * $totalTrans['complaint_num'] / $totalTrans['send_email_success_num'],2);
        }
        if ( ! (empty($totalTrans['unsubscribe_num']) ||
            empty($totalTrans['send_email_success_num']))) {
            $totalTrans['unsubscribe_rate'] =round( 100 * $totalTrans['unsubscribe_num'] / $totalTrans['send_email_success_num'],2);
        }

        if ( ! (empty($totalTrans['mailbox_unsubscribe_num']) ||
            empty($totalTrans['unsubscribe_num']))) {
            $totalTrans['mailbox_unsubscribe_rate'] = round(100 * $totalTrans['mailbox_unsubscribe_num'] / $totalTrans['unsubscribe_num'],2);
        }
        if ( ! (empty($totalTrans['mail_unsubscribe_num']) ||
            empty($totalTrans['unsubscribe_num']))) {
            $totalTrans['mail_unsubscribe_rate'] =round(100 *  $totalTrans['mail_unsubscribe_num'] / $totalTrans['unsubscribe_num'],2);
        }
        
        $skuList = self::skuDimension(['group_id'=>$group_id]);
        // 品类相关数据
        $categoryList = self::categoryDimension(['group_id'=>$group_id]);
        
        // 下单用户相关数据
        $singleUserList = self::userDimension(['group_id'=>$group_id]);
        $openandclick  = self::openAndclick(['group_id' => $group_id]);
        $orderDivision = self::orderDivision(['group_id' => $group_id]);
        $countryList   = self::countryDimension(['group_id' => $group_id]);
        $response['totalTrans'] = $totalTrans;
        $response['single']['sku'] = $skuList;
        $response['single']['country'] = $countryList;
        $response['single']['category'] = $categoryList;
        $response['single']['single_user'] = $singleUserList;
        $response['terminal']['open'] = $openandclick['open'];
        $response['terminal']['complain'] = $openandclick['complain'];
        $response['terminal']['single'] =  $orderDivision;
        return $response;
    }

    /**
     *  打开和点击分析
     *  $data[
     *  group_id => '',
     *  email_type => '',
     * 'is_click' => '全选传此参数，0 为点击，1点击'
     *
     */

    public function openAndclick($data) {
        if (empty($data['group_id'])) {
            return [];
        }

        $table = $this->prefix.$data['group_id'];
        $db =  $this->mongo->$table;
        $match = ['open_count'=>['$gte'=>1]];
        $tmp =[];
        if (isset($data['email_type'])) {
            $tmp +=['email_type' => $data['email_type']];
        }
        if(isset($data['is_click'])) {
            if (empty($data['is_click'])) { //未点击，为不等于1的
                $tmp += ['is_click' => ['$ne' =>"1"]];
            } else {
                $tmp += ['is_click' => $data['is_click']];
            }
        }
        if (! empty($tmp)) {
            $match += $tmp;
        }
        $group = ['$group'=>['_id' =>'$open_teminal','num'=>['$sum'=>1]]];
        $cond[] = ['$match'=>$match];
        $cond[] = $group;
        $orderInfo = $db->aggregate($cond)['result']; //['_id' =>'open_teminal 设备类型','num' =>'此类型数量']
        /*
         *
         *  'open' => [
                'amount' => 100,          // 数量
                'terminal' =>[
                   ['nmae' => 'web','value' => 30],
                    ['name' => 'ios','value' => 70]
                ]
            ]
         *
         */
        //设备类型 0：other 1：ios 2：android 3：pc
        $open =  [
            'sum' => 0,          // 数量
            'terminal' =>[
                ['name' => 'other','value' => "0"]
         ]];
        $terminal = [];
        if (! empty($orderInfo)) {
            foreach ( $orderInfo as $item) {
                $open['sum'] += $item['num'];
            }
            foreach ( $orderInfo as $key => $item) {
//                $terminal[$key]['value'] = $item['num'];
                //$terminal[$key]['rate'] = $item['num'] * 100 / $open['sum'];
                if ( ! isset($this->openDiviceName[$item['_id']])) {
                    if (isset($terminal[$this->openDiviceName['0']]['value'])) {
                        $terminal[$this->openDiviceName['0']]['value'] += $item['num'];
                    }else {
                        $terminal[$this->openDiviceName['0']]['value'] = $item['num'];
                    }
                    $terminal[$this->openDiviceName['0']]['name'] = $this->openDiviceName['0'];
                    continue;
                }
//                $terminal[$key]['name'] = $this->openDiviceName[$item['_id']];
                $terminal[$this->openDiviceName[$item['_id']]]['value'] = $item['num'];
                $terminal[$this->openDiviceName[$item['_id']]]['name'] = $this->openDiviceName[$item['_id']];
            }
            //$open['terminal'] = $terminal;
            $open['terminal'] = self::resetIndex($terminal);
        }


        /*
          'complain' =>[                // 邮件投诉
                'sum' => 100,          // 数量
                'terminal' =>[
                   ['nmae' => 'web','value' => 30],    //value
                   ['name' => 'ios','value' => 70]
                ]
            ]
         */
        $complain =  [
            'sum' => 0,          // 数量
            'terminal' =>[
                ['name' => 'other','value' => "0"],
            ]];
        // 退订
        $unsubCond[] = ['$match' => ['$or'=>[['is_unsubscribe'=>'1'],['mailbox_unsubscribe' =>'1'],['is_complaint'=>'1']]]];
        $unsubCond[] = ['$group'=>['_id' =>'$open_teminal','num'=>['$sum'=>1]]];

        if (! empty($tmp)) {
            $unsubCond[0]['$match'] += $tmp;
        }
        $temp = [];
        $unsubInfo = $db->aggregate($unsubCond)['result'];    //['_id' =>'open_teminal 设备类型','num' =>'此类型数量']
        if (! empty($unsubInfo)) {
            foreach ( $unsubInfo as $item) {
                $complain['sum'] += $item['num'];
            }
            foreach ( $unsubInfo as $key => $item) {

                if ( ! isset($this->openDiviceName[$item['_id']])) {
                    if (isset($temp[$this->openDiviceName['0']]['value'])) {
                        $temp[$this->openDiviceName['0']]['value'] += $item['num'];
                    }else {
                        $temp[$this->openDiviceName['0']]['value'] = $item['num'];
                    }
                    $temp[$this->openDiviceName['0']]['name'] = $this->openDiviceName['0'];
                    continue;
                }
                $temp[$this->openDiviceName[$item['_id']]]['value'] = $item['num'];
                $temp[$this->openDiviceName[$item['_id']]]['name'] = $this->openDiviceName[$item['_id']];
            }
          //  $complain['terminal'] = $terminal;
            $complain['terminal'] = self::resetIndex($temp);
        }

        $response['open'] = $open;
        $response['complain'] = $complain;
        return $response;
    }

    /**
     * 重置key
     */
    public function resetIndex($info) {
        if (empty($info)) {
            return [];
        }
        $res = null;
        $key = 0;
        foreach ($info as $index => $val) {
            $res[$key] = $val;
            ++$key;
        }
        return $res;
    }


    /**
     *  邮件下单终端分布
     *  group_id
     *  pay_status 支付状态，0 未支付，1已支付
     */
    public function orderDivision($data) {
        if (empty($data['group_id'])) {
            return [];
        }
        $table = $this->prefix.$data['group_id'];
        $db =  $this->mongo->$table;
        $match = [];
        if (isset($data['pay_status'])) {
            if (empty($data['pay_status'])) {
                $match +=['orders.pay_status' => $data['pay_status']];
            } else {
                $match +=['orders.pay_status' => ['$gte' =>"1"]];    //大于等于1 为已支付状态
            }
        }else{
            $match +=['orders.pay_status' => ['$gte' =>"0"]];    //大于等于1 为已支付状态
        }
        $cond[] = ['$unwind'=>'$orders'];
        if (! empty($match)) {
            $cond[] = ['$match'=>$match];
        }
        $orderInfo = $db->aggregate($cond)['result']; //['_id' =>'open_teminal 设备类型','num' =>'此类型数量']
        /*
         *
         *  'open' => [
                'amount' => 100,          // 数量
                'terminal' =>[
                   ['nmae' => 'web','value' => 30],
                    ['name' => 'ios','value' => 70]
                ]
            ]
         */
        //设备类型 0：other 1：ios 2：android 3：pc
        $single =  [
            'sum' => 0,          // 数量
            'terminal' =>[
                ['name' => 'web','value' => "0"]
            ]];
        $terminal = [];

        $orderIndex = [];
        if (! empty($orderInfo)) {
            foreach ( $orderInfo as $key => $item) {
                if (! isset($item['orders'])) {
                    continue;
                }
                $orders = $item['orders'];
                if (! isset($orderIndex[$orders['order_sn']])) {
                    ++$single['sum'];
                    $orderIndex[$orders['order_sn']] = $orders['order_sn'];
                    //其它的异常处理
                    if ( ! isset($this->singleDeviceName[$orders['single_terminal']])) {
                        if (! isset( $terminal[$this->singleDeviceName['0']]['value'])) {
                            $terminal[$this->singleDeviceName['0']]['name'] = $this->singleDeviceName['0'];
                            $terminal[$this->singleDeviceName['0']]['value'] = 0;
                        }
                        ++$terminal[$this->singleDeviceName['0']]['value'];
                        continue;
                    }
                    if (isset($terminal[$this->singleDeviceName[$orders['single_terminal']]]['value'])) {
                        $terminal[$this->singleDeviceName[$orders['single_terminal']]]['value'] += 1;
                    }else {
                        $terminal[$this->singleDeviceName[$orders['single_terminal']]]['value'] =1;
                        $terminal[$this->singleDeviceName[$orders['single_terminal']]]['name'] = $this->singleDeviceName[$orders['single_terminal']];
                    }
                }
            }
            $single['terminal'] = self::resetIndex($terminal);
        }
        return $single;
    }



    /**
     *  邮件下单终端分布
     *  group_id
     *  pay_status 支付状态，0 未支付，1已支付
     */
     public function actionOrderDivision() {
         $post = $_REQUEST;
         if ( ! isset($post['group_id']) || empty($post['group_id'])) {
             $this->error('group_id 不能为空');
         }
         if(isset($post['pay_status']) &&  is_numeric($post['pay_status'])) {
             $cond['pay_status'] = $post['pay_status'];
         }
         $cond['group_id'] = $post['group_id'];
//         $res = self::orderDivision(['group_id'=>15571]);
         $res = self::orderDivision($cond);
         if (empty($res)) {
             $this->error();
         }
         $this->success($res);
     }


    /**
     * group_id
     * email_type 邮件类型
     * is_click '全选传此参数，0 为点击，1点击'
     */

    public function actionOpenAndClickAnalysis() {
        $post = $_REQUEST;
        if ( ! isset($post['group_id']) || empty($post['group_id'])) {
            $this->error('group_id 不能为空');
        }
        $cond['group_id'] = $post['group_id'];
        if(isset($post['email_type']) && ! empty($post['email_type'])) {
            $cond['email_type'] = $post['email_type'];
        }
        if(isset($post['is_click']) && is_numeric($post['is_click'])) {
            $cond['is_click'] = (string)$post['is_click'];
        }
//        $res = self::openAndclick(['group_id'=>15571,'email_type' =>'5','is_click'=>'1']);
        $res = self::openAndclick($cond);
        if (empty($res)) {
            $this->error();
        }
        $this->success($res);
    }

    /**
     * 下单用户维度
     * yumao
     * 2018-6-18
     */
    public function userDimension($data)
    {
        if (empty($data['group_id'])) {
            return [];
        }

        $table = $this->prefix.$data['group_id'];
        $db = $this->mongo->$table;
        // 查出下单的用户
        $singleUserArr = $db->distinct("user_id",['orders'=>['$exists'=>"true"]]);
        $singleUserCount = count($singleUserArr);
        if (!$singleUserCount) {
            return [];
        }
        // 查出发送未打开用户数
        $sendNotOpenUserArr = $db->distinct("user_id",[
                'orders'=>['$exists'=>"true"],
                'open_email_count'=>['$lte'=>"1"],
                'send_email_count'=>['$gte'=>"2"]
            ]
        );
        $sendNotOpenUserCount = count($sendNotOpenUserArr);

        // 查出已下单用户数
        $sendHaveOrderUserArr = $db->distinct("user_id",[
                'orders'=>['$exists'=>"true"],
                'order_count'=>['$gte'=>"2"]]
        );
        $sendHaveOrderUserCount = count($sendHaveOrderUserArr);

        // 点击未下单用户数
        $clickNotOrderUserArr = $db->distinct("user_id",[
                'orders'=>['$exists'=>"true"],
                'order_count'=>['$lte'=>"1"],
                'click_email_count'=>['$gte'=>"2"]]
        );
        $clickNotOrderUserCount = count($clickNotOrderUserArr);

        // 打开未点击
        $openNotClickUserArr = $db->distinct("user_id",[
                'orders'=>['$exists'=>"true"],
                'click_email_count'=>['$lte'=>"1"],
                'open_email_count'=>['$gte'=>"2"]]
        );
        $openNotClickUserCount = count($openNotClickUserArr);

        // 首次发邮件
        $firstSendUserArr = $db->distinct("user_id",[
                'orders'=>['$exists'=>"true"],
                'send_email_count'=>['$lte'=>"1"]]
        );
        $firstSendUserCount = count($firstSendUserArr);

        // 首次购买
        $firstOrderUserArr = $db->distinct("user_id",[
                'orders'=>['$exists'=>"true"],
                'order_count'=>['$lte'=>"1"]]
        );
        $firstOrderUserCount = count($firstOrderUserArr);

        // 复购
        $rebackOrderUserArr = $db->distinct("user_id",[
                'orders'=>['$exists'=>"true"],
                'order_count'=>['$gte'=>"2"]]
        );
        $rebackOrderUserCount = count($rebackOrderUserArr);

        // 各种率
        $singUserLv = [];
//        $singUserLv['sendNotOpenUserLv'] =  round(100 *  $sendNotOpenUserCount /  $singleUserCount,2);
//        $singUserLv['sendHaveOrderUserLv'] =  round(100 *  $sendHaveOrderUserCount /  $singleUserCount,2);
//        $singUserLv['clickNotOrderUserLv'] =  round(100 *  $clickNotOrderUserCount /  $singleUserCount,2);
//        $singUserLv['openNotClickUserLv'] =  round(100 *  $openNotClickUserCount /  $singleUserCount,2);
//        $singUserLv['firstSendUserLv'] =  round(100 *  $firstSendUserCount /  $singleUserCount,2);
//        $singUserLv['firstOrderUserLv'] =  round(100 *  $firstOrderUserCount /  $singleUserCount,2);
//        $singUserLv['rebackOrderUserLv'] =  round(100 *  $rebackOrderUserCount /  $singleUserCount,2);
        $singUserLv['sendNotOpenUser'] =  $sendNotOpenUserCount;
        $singUserLv['sendHaveOrderUser'] =  $sendHaveOrderUserCount;
        $singUserLv['clickNotOrderUser'] =$clickNotOrderUserCount ;
        $singUserLv['openNotClickUser'] = $openNotClickUserCount;
        $singUserLv['firstSendUser'] =  $firstSendUserCount ;
        $singUserLv['firstOrderUser'] =  $firstOrderUserCount ;
        $singUserLv['rebackOrderUser'] =  $rebackOrderUserCount;
        return $singUserLv;
    }


    /**
     *  sku 为维度
     *  group_id
     *  $page = 0
     *  $pageSize = 10
     *  authore xianxuefeng
     */
    public function categoryDimension($data) {
        if (empty($data['group_id'])) {
            return [];
        }
        $table = $this->prefix.$data['group_id'];
        $db = $this->mongo->$table;
        $orderList = $db->find(["orders"=>['$exists'=>"true"]],['orders'=>1,'_id'=>0]);
        $orderList = iterator_to_array($orderList);

        if (empty($orderList)) {   //没有更多信息
            return [];
        }
        /*
           [
                'goods_sn' => $val['_id'],
                'category_id' => $val['category_id'][0],
                'order_num' => 0,
                'order_amount' =>0,
                'pay_order_num' => 0,
                'pay_order_amount' =>0,
                'single_user_num' => 0,
                'pay_order_rate' => 0,
                'pay_amount_rate' => 0
            ]
         */

        $skuList = [];
        $orderIndex = [];
        foreach($orderList as $val) {
            if (!isset($val['orders'][0]['goods_sn']) || !is_array($val['orders'])) {
                continue;
            }
            foreach ($val['orders'] as $v) {
                if (!isset($v['goods_sn'])) {
                    continue;
                }
                //skuList[goods_sn] 为空时，初始化
                if (!isset($skuList[$v['category_id']])) {
                    $skuList[$v['category_id']]['goods_sn'] = $v['goods_sn'];
                    $skuList[$v['category_id']]['category_id'] = $v['category_id'];
                    $skuList[$v['category_id']]['category_name'] = isset($v['category_name'])? $v['category_name']: '';
                    $skuList[$v['category_id']]['order_goods_num'] = 0;
                    $skuList[$v['category_id']]['goods_name'] = $v['goods_name'];
                    $skuList[$v['category_id']]['order_num'] = 0;
                    $skuList[$v['category_id']]['order_amount'] = 0;
                    $skuList[$v['category_id']]['pay_order_num'] = 0;
                    $skuList[$v['category_id']]['pay_order_amount'] = 0;
                    $skuList[$v['category_id']]['single_user_num'] = 1;    //初始化订单用户数
                    $skuList[$v['category_id']]['pay_order_rate'] = 0;    // 支付订单率
                    $skuList[$v['category_id']]['pay_amount_rate'] = 0;    //支付订单金额率
                    $skuList[$v['category_id']]['pay_single_user_num'] = 0;    //支付订单用户数默认为1
                }
                $skuList[$v['category_id']]['user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                if (isset($orderIndex[$v['order_sn']])) {     //去除重复的订单
                    continue;
                }
                $orderIndex[$v['order_sn']] = $v['order_sn'];
                ++$skuList[$v['category_id']]['order_num'];
                $skuList[$v['category_id']]['order_amount'] += $v['order_amount'];
                $skuList[$v['category_id']]['order_goods_num'] += isset($v['goods_number'])? $v['goods_number'] : 0;
                if ($v['pay_status'] >= 1) {   //支付订单
                    $skuList[$v['category_id']]['pay_user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                    ++$skuList[$v['category_id']]['pay_order_num'];
                    $skuList[$v['category_id']]['pay_order_amount'] += $v['order_amount'];
                }
            }
        }
        unset($data,$table,$db,$orderList);
        // 统计支付订单的订单率和金额率
        foreach ( $skuList as & $val) {
            $val['single_user_num'] = isset($val['user_id_array']) ? count($val['user_id_array']) : 0;            // 下单用户数
            $val['pay_single_user_num'] =isset($val['pay_user_id_array']) ? count($val['pay_user_id_array']) : 0;    // 支付订单用户数
            if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
            }
            if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2);
            }
            unset($val['user_id_array'],$val['pay_user_id_array']);
        }
        return self::resetIndex($skuList);
    }


    /**
     *  sku 为维度
     *  group_id
     *  $page = 0
     *  $pageSize = 10
     */
    public function skuDimension($data) {
        if (empty($data['group_id'])) {
            return [];
        }
        $table = $this->prefix.$data['group_id'];
        $db = $this->mongo->$table;
        $orderList = $db->find(["orders"=>['$exists'=>"true"]],['orders'=>1,'_id'=>0]);
        $orderList = iterator_to_array($orderList);
        if (empty($orderList)) {   //没有更多信息
            return [];
        }
        /*
           [
                'goods_sn' => $val['_id'],
                'category_id' => $val['category_id'][0],
                'order_num' => 0,
                'order_amount' =>0,
                'pay_order_num' => 0,
                'pay_order_amount' =>0,
                'single_user_num' => 0,
                'pay_order_rate' => 0,
                'pay_amount_rate' => 0
            ]
         */

        $skuList = [];
        foreach($orderList as $val) {
            if (!isset($val['orders'][0]['goods_sn']) || !is_array($val['orders'])) {
                continue;
            }
            foreach ($val['orders'] as $v) {
                if (!isset($v['goods_sn'])) {
                    continue;
                }
                //skuList[goods_sn] 为空时，初始化
                if (!isset($skuList[$v['goods_sn']])) {
                    $skuList[$v['goods_sn']]['goods_sn'] = $v['goods_sn'];
                    $skuList[$v['goods_sn']]['category_id'] = $v['category_id'];
                    $skuList[$v['goods_sn']]['category_name'] = isset($v['category_name'])? $v['category_name']: '';
                    $skuList[$v['goods_sn']]['order_goods_num'] = 0;   //商品数量
                    $skuList[$v['goods_sn']]['goods_name'] = $v['goods_name'];
                    $skuList[$v['goods_sn']]['order_num'] = 0;
                    $skuList[$v['goods_sn']]['order_amount'] = 0;
                    $skuList[$v['goods_sn']]['pay_order_num'] = 0;
                    $skuList[$v['goods_sn']]['pay_order_amount'] = 0;
                    $skuList[$v['goods_sn']]['single_user_num'] = 1;    //初始化订单用户数
                    $skuList[$v['goods_sn']]['pay_order_rate'] = 0;    // 支付订单率
                    $skuList[$v['goods_sn']]['pay_amount_rate'] = 0;    //支付订单金额率
                    $skuList[$v['goods_sn']]['pay_single_user_num'] = 0;    //支付订单用户数默认为1
                }
                $skuList[$v['goods_sn']]['user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                ++$skuList[$v['goods_sn']]['order_num'];
                $skuList[$v['goods_sn']]['order_amount'] += $v['order_amount'];
                $skuList[$v['goods_sn']]['order_goods_num'] += isset($v['goods_number'])? $v['goods_number'] : 0;
                if ($v['pay_status'] >= 1) {   //支付订单
                    $skuList[$v['goods_sn']]['pay_user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                    ++$skuList[$v['goods_sn']]['pay_order_num'];
                    $skuList[$v['goods_sn']]['pay_order_amount'] += $v['order_amount'];
                }
            }
        }
        unset($data,$table,$db,$orderList);
        // 统计支付订单的订单率和金额率
        foreach ( $skuList as & $val) {
            $val['single_user_num'] = isset($val['user_id_array']) ? count($val['user_id_array']) : 0;            // 下单用户数
            $val['pay_single_user_num'] =isset($val['pay_user_id_array']) ? count($val['pay_user_id_array']) : 0;    // 支付订单用户数
            if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
            }
            if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2);
            }
            unset($val['user_id_array'],$val['pay_user_id_array']);
        }
        return self::resetIndex($skuList);
    }


    /**
     *  country 为维度
     *  group_id
     *  $page = 0
     *  $pageSize = 10
     */
    public function countryDimension($data) {
        if (empty($data['group_id'])) {
            return [];
        }
        $table = $this->prefix.$data['group_id'];
        $db = $this->mongo->$table;
        $orderList = $db->find(["orders"=>['$exists'=>"true"]],['orders'=>1,'_id'=>0]);
        if (empty($orderList)) {
            return [];
        }
        $orderList = iterator_to_array($orderList);
        if (empty($orderList)) {   //没有更多信息
            return [];
        }
        $countryList = [];
        $orderIndex = [];
        foreach($orderList as $val) {
            if (!isset($val['orders'][0]['country']) || ! is_array($val['orders'])) {
                continue;
            }
            foreach ($val['orders'] as $v) {
                if (!isset($v['country'])) {
                    continue;
                }
                //skuList[goods_sn] 为空时，初始化
                if (!isset($skuList[$v['country']])) {
                    $countryList[$v['country']]['country'] = $v['country'];
                    $countryList[$v['country']]['category_id'] = $v['category_id'];
                    $countryList[$v['country']]['order_num'] = 0;
                    $countryList[$v['country']]['order_amount'] = 0;
                    $countryList[$v['country']]['pay_order_num'] = 0;
                    $countryList[$v['country']]['pay_order_amount'] = 0;
                    $countryList[$v['country']]['single_user_num'] = 1;    //初始化订单用户数
                    $countryList[$v['country']]['pay_order_rate'] = 0;    // 支付订单率
                    $countryList[$v['country']]['pay_amount_rate'] = 0;    //支付订单金额率
                    $countryList[$v['country']]['pay_single_user_num'] = 0;    //支付订单用户数默认为1
                }
                if (isset($orderIndex[$v['order_sn']])) {     //去除重复的订单
                    continue;
                }
                $orderIndex[$v['order_sn']] = $v['order_sn'];
                $countryList[$v['country']]['user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                ++$countryList[$v['country']]['order_num'];
                $countryList[$v['country']]['order_amount'] += $v['order_amount'];
                if ($v['pay_status'] >= 1) {   //支付订单
                    $countryList[$v['country']]['pay_user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                    ++$countryList[$v['country']]['pay_order_num'];
                    $countryList[$v['country']]['pay_order_amount'] += $v['order_amount'];
                }
            }
        }
        unset($data,$table,$db,$orderList);
        // 统计支付订单的订单率和金额率
        foreach ( $countryList as & $val) {
            $val['single_user_num'] = isset($val['user_id_array']) ? count($val['user_id_array']) : 0;            // 下单用户数
            $val['pay_single_user_num'] =isset($val['pay_user_id_array']) ? count($val['pay_user_id_array']) : 0;    // 支付订单用户数
            if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
            }
            if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2);
            }
            unset($val['user_id_array'],$val['pay_user_id_array']);
        }
        return self::resetIndex($countryList);
        return $orderList;
    }



    /**
     * sku 维度
     */
    public function actionSku() {
        $post = $_REQUEST;
        if ( ! isset($post['group_id']) || empty($post['group_id'])) {
            $this->error('group_id 不能为空');
        }
        if (! isset($post['page'])) {
            $post['page'] = 0;
        }

        $cond['group_id'] = $post['group_id'];
        $cond['page'] = $post['page'];

        $res = self::skuDimension($cond);
        if (empty($res)) {
            $this->error("没有更多信息了");
        }
        $this->success($res);
    }


    /**
     *  country 国家维度
     */
    public function actionCountry() {
        $post = $_REQUEST;
        if ( ! isset($post['group_id']) || empty($post['group_id'])) {
            $this->error('group_id 不能为空');
        }
        if (! isset($post['page'])) {
            $post['page'] = 0;
        }
        $cond['group_id'] = $post['group_id'];
        $cond['page'] = $post['page'];
        $res = self::countryDimension($cond);
//        $res = self::countryDimension(['group_id'=>15571]);
        if (empty($res)) {
            $this->error("没有更多信息了");
        }
        $this->success($res);
    }

    /**
     * 协议模拟数据
     *
     */
    public function actionTest() {
        $info['totalTrans'] = [                 // 邮件转化分析
            'order_amount' => 0,                // 订单总额
            'pay_order_amount' => 0,            // 付款总额 ,note :汇总统计该发送分组的已支付订单总金额, 币种为美元（$）。
            'order_num' => 0,                   // 订单数,note : 汇总统计该发送分组的所有订单数（单位：个），按订单号汇总
            'pay_order_num' => 0,               // 付款订单数 ,note : 汇总统计该发送分组的所有已支付订单数（单位：个），按订单号汇总。
            'pay_amount_rate' => 0,             // 付款金额率 ,note : 付款金额率=[付款总额/订单总额]*100%
            'pay_order_rate' => 0,              // 付款订单率 ,note : 付款订单率=[付款订单数/订单数] *100%
            'send_email_num' => 0,           // 邮件发送数量
            'send_email_success_num' => 0,   // 邮件发送成功的数量, note : 渠道返回的该发送分组发送成功用户数。
            'email_success_rate' => 0,          // 邮件发送成功率 , note :  渠道返回的该发送分组发送成功用户数。
            'email_open_num' => 0,           // 邮件打开的数量 , note : 取该发送分组的独立打开用户数
            'email_open_rate' => 0,             // 邮件打开率 , note : 打开率=[独立打开用户数/发送成功] *100%
            'user_click_num' => 0,           // 用户点击邮件数量（用户点击）, note : 取该发送分组的独立点击用户数
            'user_click_rate' => 0,             // 用户点击邮件率（用户点击率）, note : 点击转化率=[独立点击用户数/独立打开用户数] *100%
            'single_user_num' => 0,     // 下单用户数 (汇总统计该发送分组的下过订单的用户数（按网站用户ID汇总）)
            'single_user_rate' => 0,    // 下单用户率 (用户下单率=[独立点击用户数/独立打开用户数] *100%)
            'pay_user_num' => 0,     // 付费用户数(用户付款) ,note :汇总统计该发送分组的下过订单并且已支付的用户数（按网站用户ID汇总）
            'pay_user_rate' => 0,       // 付费用户率 note : 用户付款率=[用户付款 /用户下单] *100%
            'bounces_num' => 0,         // 弹回数 note: 弹回总数=硬弹用户数+软弹用户数
            'bounces_rate' => 0,        // 弹回率 note: 弹回率=[弹回总数/发送总量]*100%
            'hard_bounces_num' => 0,    // 硬弹数
            'hard_bounces_rate' => 0,   // 硬弹率 note: 硬弹率=[硬弹用户数/弹回总数]*100%
            'soft_bounces_num' => 0,    // 软弹数
            'soft_bounces_rate' => 0,   // 软弹率 note: 软弹率=[硬弹用户数/弹回总数]*100%
            'complaint_num' => 0,       // 投诉数
            'complaint_rate' => 0,      // 投诉率 note: 投诉率=[投诉用户数/发送成功数] *100%
            'unsubscribe_num' => 0,     // 退订数
            'unsubscribe_rate' => 0,    // 退订率 note: 投诉率=[投诉用户数/发送成功数] *100%
            'mailbox_unsubscribe_num' =>0, // 邮箱退订数
            'mail_unsubscribe_num' => 0,   //邮件退订数
            'mailbox_unsubscribe_rate' => 0, //  邮箱退订率
            'mail_unsubscribe_rate' => 0,    // 邮件退订率
        ];

        $info['terminal'] = [             // 邮件打开、
            'open' => [
                'amount' => 100,          // 数量
                'terminal' =>[
                    ['nmae' => 'web','value' => 30],
                    ['name' => 'ios','value' => 70]
                ]
            ],
            'complain' =>[                // 邮件投诉
                'amount' => 100,          // 数量
                'terminal' =>[
                    ['nmae' => 'web','value' => 30],
                    ['name' => 'ios','value' => 70]
                ]
            ],
            'single' =>[                  // 下单
                'amount' => 100,          // 数量
                'terminal' =>[
                    ['nmae' => 'web','value' => 30],
                    ['name' => 'ios','value' => 70]
                ]
            ]
        ];

        $info['single'] = [          // 邮件下单分析
            'sku' => [[
                'goods_sn' => '0000',
                'goods_name' => '暂无名称',
                'category_id' => 12,  //分类id
                'category_name' => '分类名称',
                'single_user_num' => 100, //下单用户数
                'order_num' => 12,     // 订单数量
                'pay_order_amount' => 100,  //付费订单金额
                'pay_order_rate' => '20%', //付费订单率
                'order_amount' => 200,     //订单总金额
                'pay_amount_rate' => '30%', // 付款金额率 note:付款金额率=[付款总额/订单总额]*100%
            ]
            ],
            'category' =>[[
                'category_id' => 12, //商品分类
                'single_user_num' => 100, //下单用户数
                'order_num' => 12,     // 订单数量
                'pay_order_amount' => 100,  //付费订单金额
                'pay_order_rate' => '20%', //付费订单率
                'order_amount' => 200,     //订单总金额
                'pay_amount_rate' => '30%', // 付款金额率 note:付款金额率=[付款总额/订单总额]*100%
            ]],
            'single_user' =>[
                'order_rate' => '40%',  //已经下单率 note: 该发送分组的下单用户中历史已下单的用户占总下单用户比例
                'no_single_click_rate' => '30%', //点击未下单 note: 该发送分组的下单用户中历史点击邮件但未下单的用户占总下单用户比例
                'open unclick_rate' => '3%',     //打开未点击,note: 该发送分组的下单用户中历史打开未点击的用户占总下单用户比例
                'first_mail_rate' => '7%',       //首次发邮件, note: 该发送分组的下单用户中首次发邮件的用户占总下单用户比例
                'first_purchase_rate' => '10%',  //首次购买, note: 该发送分组的下单用户中首次购买的用户占总下单用户比例。首次购买指注册且下单频次为1的用户
                'buy_again_rate' => '10%',       //再次购买, note: 该发送分组的下单用户中下过2个订单以上的用户占总下单用户比例。复购注册且下单频次2以上的用户
            ],
            'country' => [
                'country_name' => '美国',
                'single_user_num' => 100, //下单用户数
                'order_num' => 12,     // 订单数量
                'pay_order_amount' => 100,  //付费订单金额
                'pay_order_rate' => '20%', //付费订单率
                'order_amount' => 200,     //订单总金额
                'pay_amount_rate' => '30%', // 付款金额率 note:付款金额率=[付款总额/订单总额]*100%
            ]
        ];
        $this->success($info);
    }

    public function actionEmailTypeList() {
        $email_type_list = [
            'others' => "1",
            'gmail'  => "2",
            "yahoo"  => "3",
            "hotmail" => "4",
            "live" =>"4",
            "aol"  => "5"
        ];
        $this->success($email_type_list);
    }

    /**
     * 显示用户分群
     * group_id
     * import_type
     * group_name
     * @return string
     */
    public function actionShowUserGroup()
    {
        yii::$app->params['now_addr'] = "发送管理";
        $method = yii::$app->request->getMethod();
        $mailGroupId = yii::$app->request->$method("group_id");
        $import_type = yii::$app->request->$method("import_type");
        $site = yii::$app->request->$method("site");

        if (empty($mailGroupId)) {
            $this->sysMsg('警告', '数据不完整，缺少分组id!',
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $groupModel = new MailGroup();
        $group = $groupModel->getGroupById($mailGroupId);
        $data = $group;
        $detail = json_decode($group['user_group_detail'], true);
        if (empty($detail)) {
            $detail = [];
        }
        $preview = ["user_define" => [], "sys" => [], "exclude" => []];

        foreach ($detail as $key => $value) {
            $formData = json_decode($value['form_data'], true);
            $item = $this->getPreviewItem($formData);

            $detail[$key]['item'] = $item;
            $preview[$value['type']][] = $detail[$key];
        }
        $data['preview'] = $preview;
//        $analysis = new AnalysisMailGroupController();
//        $totalTransformation = $analysis->totalTransformation(['group_id'=>$mailGroupId]);
        $m =  $this->mongo;
        $table = $this->res_backup;
        $collection  =$m->$table;
        $analysisInfo = $collection->find(['group_id'=>$mailGroupId],['_id'=>0,'group_id'=>0]);
        $res = iterator_to_array($analysisInfo);
       
        if (empty($res)) {
            $totalTransformation = self::totalTransformation(['group_id'=>$mailGroupId]);
        } else {
            $totalTransformation = $res[0];
        }

        $data['group_name'] = $group['group_name'];
        if (! empty($import_type)) {
            //去除尾部时间戳 LR_test_langria_180712_1531356909
           // $data['group_name'] = $group['group_name'];
            $length = strripos( $group['group_name'],"_");
            $group_name=  substr( $group['group_name'],0,$length);
            $res = self::exportExcel($totalTransformation,['name' => $group_name,'type' => $import_type]);
            if (empty($res)) {
                $this->sysMsg('警告', '下载信息为空',
                    [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
            return;
        }

        if ($data['site_id'] == 31 || ($data['site_id']==25 && $data['group_type']==3) ) {
            $userGroupIdArr = [];
            if ($data['preview']['user_define']) {
                foreach ($data['preview']['user_define'] as $userDefineOne) {
                    $userGroupIdArr[] = $userDefineOne['user_group_id'];
                }
            }
            if ($data['preview']['exclude']) {
                foreach ($data['preview']['exclude'] as $excludeOne) {
                    $userGroupIdArr[] = $excludeOne['user_group_id'];
                }
            }

            // 根据user_group_id
            $userGroup= new UserGroup();
            $userGroupInfoArr = $userGroup->getUserGroupByIdArr($userGroupIdArr);
            $userGroupInfoArrDeal = [];
            foreach ($userGroupInfoArr as $userGroupInfoArrVal) {
                $userGroupInfoArrDeal[$userGroupInfoArrVal['user_group_id']] = $userGroupInfoArrVal;
            }
            if ($data['preview']['user_define']) {
                foreach ($data['preview']['user_define'] as $key => $userDefineOne) {
                    if (!empty($userGroupInfoArrDeal[$userDefineOne['user_group_id']])) {
                        $data['preview']['user_define'][$key]['item'][0]['name'] = $data['preview']['user_define'][$key]['user_group_name'] = $userGroupInfoArrDeal[$userDefineOne['user_group_id']]['user_group_name'];
                        $data['preview']['user_define'][$key]['item'][0]['count'] = $data['preview']['user_define'][$key]['count'] = $userGroupInfoArrDeal[$userDefineOne['user_group_id']]['user_count'];
                    } else {
                        $data['preview']['user_define'][$key]['item'][0]['name'] = $data['preview']['user_define'][$key]['user_group_name'] = "";
                        $data['preview']['user_define'][$key]['item'][0]['count'] = $data['preview']['user_define'][$key]['count'] = 0;
                    }

                }
            }
            if ($data['preview']['exclude']) {
                foreach ($data['preview']['exclude'] as $key => $excludeOne) {
                    if (!empty($userGroupInfoArrDeal[$excludeOne['user_group_id']])) {
                        $data['preview']['exclude'][$key]['item'][0]['name'] = $data['preview']['exclude'][$key]['user_group_name'] = $userGroupInfoArrDeal[$excludeOne['user_group_id']]['user_group_name'];
                        $data['preview']['exclude'][$key]['item'][0]['count'] = $data['preview']['exclude'][$key]['count'] = $userGroupInfoArrDeal[$excludeOne['user_group_id']]['user_count'];
                    } else {
                        $data['preview']['exclude'][$key]['item'][0]['name'] = $data['preview']['exclude'][$key]['user_group_name'] = "";
                        $data['preview']['exclude'][$key]['item'][0]['count'] = $data['preview']['exclude'][$key]['count'] = 0;
                    }
                }
            }
//            return $this->render("//marketing/mail-group/show-ebay-group", ["data" => $data]);
            return $this->render("//marketing/mail-group/show-user-group", ["data" => $data,'info' => $totalTransformation,'type' =>'handImport']);
        } else {
            return $this->render("//marketing/mail-group/show-user-group", ["data" => $data,'info' => $totalTransformation,'type'=>'autoImport']);
        }

//        return $this->render("//marketing/mail-group/show-user-group", ["data" => $data,'info' => $totalTransformation]);
    }

    /**
     * 获取预览中的选项
     * @param $formData
     * @return array
     */
    public function getPreviewItem($formData)
    {
        $item = [];

        $freqNameArr = [
            "1" => "1次",
            "2" => "2~4次",
            "3" => "5~7次",
            "4" => "8~9次",
            "5" => "10次以上"
        ];
        $orderMoneyArr = [
            "1" => "0$~50$",
            "2" => "50$~100$",
            "3" => "100$~200$",
            "4" => "200$~300$",
            "5" => "300$~500$",
            "6" => '500$以上'
        ];
        // 注册
        if (0 != $formData['register_state']) {
            $regName = "";
            if (1 == $formData['register_time_type']) {        // 指定近几天
                if (isset($formData['register_near_days']) && is_numeric($formData['register_near_days'])) {
                    $regName .= "近{$formData['register_near_days']}天 ";
                }
            } else {
                if (!empty($formData['register_start_time'])) {
                    $regName .= "{$formData['register_start_time']}";
                }
                if (!empty($formData['register_end_time'])) {
                    $regName .= "~{$formData['register_end_time']} ";
                }
            }
            if (1 == $formData['register_state']) {
                $regName .= "未注册";
            } else {
                $regName .= "注册";
            }
            //$regCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'], [], [], []);
            $item[] = ["name" => $regName, "count" => ""];
        }

        // 登录
        if (0 != $formData['login_state']) {
            $name = "";
            if (1 == $formData['login_time_type']) {        // 指定近几天
                if (isset($formData['login_near_days']) && is_numeric($formData['login_near_days'])) {
                    $name .= "近{$formData['login_near_days']}天 ";
                }
            } else {
                if (!empty($formData['login_start_time'])) {
                    $name .= "{$formData['login_start_time']}";
                }
                if (!empty($formData['login_end_time'])) {
                    $name .= "~{$formData['login_end_time']} ";
                }
            }
            if (1 == $formData['login_state']) {
                $name .= "从未登录";
            } else {
                $name .= "登录";
            }
            if (!empty($formData['login_frequency']) && key_exists($formData['login_frequency'], $freqNameArr)) {
                $name .= " {$freqNameArr[$formData['login_frequency']]} ";
            }
            //$loginCount = $userGroupModel->getCount($siteName, 0, [], $data['login_con'], [], []);
            $item[] = ["name" => $name, "count" => ""];
        }

        // 下单
        if (0 != $formData['order_state']) {
            $name = "";
            if (1 == $formData['order_time_type']) {    // 指定近几天
                if (isset($formData['order_near_days']) && is_numeric($formData['order_near_days'])) {
                    $name .= "近{$formData['order_near_days']}天 ";
                }
            } else {
                if (!empty($formData['order_start_time'])) {
                    $name .= "{$formData['order_start_time']}";
                }
                if (!empty($formData['order_end_time'])) {
                    $name .= "~{$formData['order_end_time']} ";
                }
            }

            if (1 == $formData['order_state']) {
                $name .= "从未下单";
            } else {
                $name .= "下单";
            }

            if (!empty($formData['order_frequency']) && key_exists($formData['order_frequency'], $freqNameArr)) {
                $name .= " {$freqNameArr[$formData['order_frequency']]} ";
            }
            //$orderCount = $userGroupModel->getCount($siteName, 0, [], [], $data['order_con'], []);
            $item[] = ["name" => $name, "count" => ""];
        }


        if (0 != $formData['mail_state']){
            $name = "";
            if (1 == $formData['mail_time_type']) {
                if (isset($formData['mail_near_days']) && is_numeric($formData['mail_near_days'])) {
                    $name .= "近{$formData['mail_near_days']}天 ";
                }
            } else {
                if (!empty($formData['mail_start_time'])) {
                    $name .= "{$formData['mail_start_time']}";
                }
                if (!empty($formData['mail_end_time'])) {
                    $name .= "~{$formData['mail_end_time']} ";
                }
            }
            $mailStateArr = [1 => "从未发送", 3 => "已发送", 2 => "发送未打开", 4 => "邮件打开", 5 => "打开未点击", 6 => "打开并点击"];
            if (key_exists($formData['mail_state'], $mailStateArr)) {
                $name .= " " . $mailStateArr[$formData['mail_state']];
            }
            if (!empty($formData['mail_open_frequency']) && key_exists($formData['mail_open_frequency'], $freqNameArr)) {
                $name .= " 且打开次数{$freqNameArr[$formData['mail_open_frequency']]} ";
            }
            if (!empty($formData['mail_click_frequency']) && key_exists($formData['mail_click_frequency'], $freqNameArr)) {
                $name .= " 且点击次数{$freqNameArr[$formData['mail_click_frequency']]} ";
            }
            //$mailCount = $userGroupModel->getCount($siteName, 0, [], [], [], $data['mail_con']);
            $item[] = ["name" => $name, "count" => ""];

        }

        // 品类相关
        $category = new Category();
        $selectNameArr = [];
        $selectNameStr = "";

        // 单分类
        if (!empty($formData['relation']) && !empty($formData['category_id']) && is_array($formData['category_id'])) {
            foreach ($formData['category_id'] as $categoryId) {
                if (!empty($categoryId)) {
                    $selectNameTmp = $category->getCateNameById($categoryId,$formData['site_id']);
                    if (!empty($selectNameTmp)) {
                        $selectNameArr[] = $selectNameTmp;
                    }
                }
            }


            if ($formData['relation'] == 1) {
                $selectNameStr = join(' <font color="blue">and</font> ',$selectNameArr);
            } else {
                $selectNameStr = join(' <font color="blue">or</font> ',$selectNameArr);
            }

        }

        // 多级分类
        if (!empty($formData['relation']) && !empty($formData['category_id_info']) && is_array($formData['category_id_info'])) {
            $selectNameArr = [];
            $selectNameStr = "";
            $categoryIdArr = [];
            $categoryTempStr = "";
            foreach ($formData['category_id_info'] as $categoryIdInfoVal) {
                if (!empty($categoryIdInfoVal)){

                    $categoryTempId = 0;

                    $categoryIdInfoValLen = count($categoryIdInfoVal);
                    $categoryTempId = $categoryIdInfoVal['category_id'.$categoryIdInfoValLen];

                    if (!empty($categoryTempId)) {
                        $categoryIdArr[] = $categoryTempId;
                    }
                    // if (!empty($categoryTempStr)) {
                    // $selectNameArr[] = trim($categoryTempStr,"/");
                    // }
                }
            }
            if (!empty($categoryIdArr)) {
                $categoryIdArr = array_unique($categoryIdArr);
            }

            foreach ($categoryIdArr as $categoryIdVal) {
                $categoryTempStr = $category->getCateNameById($categoryIdVal,$formData['site_id']);
                if (!empty($categoryTempStr)) {
                    $selectNameArr[] = $categoryTempStr;
                }
            }
            if ($formData['relation'] == 1) {
                $selectNameStr = join(' <font color="blue">and</font> ',$selectNameArr);
            } else {
                $selectNameStr = join(' <font color="blue">or</font> ',$selectNameArr);
            }
        }
        // RG 已下单
        if ($formData['site_id'] == 11 && 2 == $formData['order_state']) {
            $shop_num_min = empty($formData['shop_num_min']) ? 0 : $formData['shop_num_min'];
            $shop_num_max = empty($formData['shop_num_max']) ? 0 : $formData['shop_num_max'];
            $pay_money_min = empty($formData['pay_money_min']) ? 0 : $formData['pay_money_min'];
            $pay_money_max = empty($formData['pay_money_max']) ? 0 : $formData['pay_money_max'];
            $name ='';
            if (! empty($shop_num_min) || ! empty($shop_num_max) ) {
                $name .= " 商品数量  {$shop_num_min} ~ {$shop_num_max}件 ";
            }
            if (! empty($pay_money_min) || ! empty($pay_money_max) ) {
                $name .= " 付款金额 ".'$'."{$pay_money_min} ~ ".'$'. $pay_money_max;
            }
            if ( ! empty($name)) {
                $name = " 近{$formData['order_near_days']}天 " . $name;
                $item[] = ["name" => $name, "count" => ""];
            }
        }

        // RG 多级品类展示
        if ($formData['site_id'] == 11 && isset($formData['user_behavior_category_id_info'],$formData['relation'])
            && is_array($formData['user_behavior_category_id_info']) ) {
            $selectNameArr = [];
            $selectNameStr = "";
            foreach ($formData['user_behavior_category_id_info'] as $categoryId) {
                $selectNameTmp = $category->getRgCateNameById($categoryId,$formData['site_id']);
                if (!empty($selectNameTmp)) {
                    $selectNameArr[] = $selectNameTmp;
                }
            }
            if ($formData['relation'] == 1 && ! empty($selectNameArr)) {
                $selectNameStr .= "品类偏好： ".join(' <font color="blue">and</font> ',$selectNameArr);
            }
            if ($formData['relation'] == 2 && ! empty($selectNameArr)) {
                $selectNameStr .= "品类偏好： ".join(' <font color="blue">or</font> ',$selectNameArr);
            }
        }
        //用户标签
        if (!empty($formData['userLabel'])){
            $userLabelInfo = (new UserLabelQueue())->getByQueueId($formData['userLabel']);
            $name = "用户标签组：".(isset($userLabelInfo['queue_name']) ? $userLabelInfo['queue_name'] : '');
            $item[] = ["name" => $name, "count" => ""];
        }

        if (!empty($selectNameStr)) {
            $item[] = ["name" => $selectNameStr, "count" => ""];
        }

        return $item;
    }

    /**
     * 单封邮件漏斗分析
     * template_id
     * reservation_time  2018-06-07+-+2018-07-07
     * @return ['data'=>[],'info' => '漏斗分析数据']
     *
     */
    public function actionMailAnalysisTest()
    {
        $method = yii::$app->request->getMethod();
       // $mailGroupId = yii::$app->request->$method("group_id");
        $template_id = yii::$app->request->$method("template_id");
        $reservation_time = yii::$app->request->$method("reservation_time");
        if (empty($template_id)) {
            $this->sysMsg('警告', '数据不完整，缺少模板template_id',
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $where = '';
        if (empty($template_id)) {
            $where = "template_id = {$template_id} and ";
        }
        if (  ! empty($reservation_time)  ) {
            $timelist = explode(' - ',$reservation_time);
//            $start_time = strtotime($timelist[0]);
//            $end_time = strtotime($timelist[1]) + 24*60*60;
            $start_time = Yii::$app->systime->strtotime($timelist[0]);
            $end_time = Yii::$app->systime->strtotime($timelist[1].' +24 hours');
            $where .= " add_date between {$start_time} and {$end_time} ";
        }
        if ( ! empty($where)) {
            $where = " where ".$where;
        }

        //查询sql
        $sql = "select group_id,group_name from mail_group {$where}";
        $categoryInfo = yii::$app->db->createCommand($sql)->queryAll();

        $m =  $this->mongo;
        $table = $this->res_backup;
        $collection  =$m->$table;
        $analysisInfo = $collection->find(['group_id'=>16860],['_id'=>0,'group_id'=>0]);
        $res = iterator_to_array($analysisInfo);
        if (empty($res)) {
            $totalTransformation = self::totalTransformation(['group_id'=>16860]);
        } else {
            $totalTransformation = $res[0];
        }
        // echo "<pre/>";
        // print_r($totalTransformation);die;
        return $this->render("/marketing/mail-group/mail-analysis", ['data' => $categoryInfo,'info' => $totalTransformation]);
    }


    /**
     *  单封漏斗分析
     *
     * date 2018/7/7
     * import_type sku ,category,country
     * author xianxuefeng
     */
    public function actionMailAnalysis() {

        $method = yii::$app->request->getMethod();
        // $mailGroupId = yii::$app->request->$method("group_id");
        $template_id = yii::$app->request->$method("template_id");
        $reservation_time = yii::$app->request->$method("reservation_time");
        $import_type = yii::$app->request->$method("import_type");
        $template_name = yii::$app->request->$method("template_name");
        $site = yii::$app->request->$method("site");
        
        if (empty($template_id)) {
            $this->sysMsg('警告', '数据不完整，缺少模板template_id',
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $where = '';
        if (! empty($template_id)) {
            $where = "template_id = {$template_id} and is_inside_test = 0 and ";
        }
        $formData['startTime'] = '2017-10-10';
        $formData['endTime'] = '2017-10-11';
        if (  ! empty($reservation_time)  ) {
            $timelist = explode(' - ',$reservation_time);
            if (isset($timelist[1]) || !empty($timelist[1]) ) {
//                $startTime = strtotime($timelist[0]);
//                $endTime = strtotime($timelist[1]) +60*60*24-1;
                $startTime = Yii::$app->systime->strtotime($timelist[0]);
                $endTime = Yii::$app->systime->strtotime($timelist[1].' +24 hours');
                $formData['startTime'] = $timelist[0];
                $formData['endTime'] = $timelist[1] ;
                $where .= " add_date between {$startTime} and {$endTime} and ";
            }
        }
        if ( ! empty($where)) {
            $where = " where ".$where;
            $where = rtrim($where,'and ');
        } 

        //查询sql
        $sql = "select group_id,group_name from mail_group {$where}";
        $categoryInfo = yii::$app->db->createCommand($sql)->queryAll();

        $m =  $this->mongo;
        $table = $this->res_backup;
        $collection  =$m->$table;
        
        $response['totalTrans'] = [                 // 邮件转化分析
            'order_amount' => 0,                // 订单总额
            'pay_order_amount' => 0,            // 付款总额 ,note :汇总统计该发送分组的已支付订单总金额, 币种为美元（$）。
            'order_num' => 0,                   // 订单数,note : 汇总统计该发送分组的所有订单数（单位：个），按订单号汇总
            'pay_order_num' => 0,               // 付款订单数 ,note : 汇总统计该发送分组的所有已支付订单数（单位：个），按订单号汇总。
            'pay_amount_rate' => 0,             // 付款金额率 ,note : 付款金额率=[付款总额/订单总额]*100%
            'pay_order_rate' => 0,              // 付款订单率 ,note : 付款订单率=[付款订单数/订单数] *100%
            'send_email_num' => 0,           // 邮件发送数量
            'send_email_success_num' => 0,   // 邮件发送成功的数量, note : 渠道返回的该发送分组发送成功用户数。
            'email_success_rate' => 0,          // 邮件发送成功率 , note :  渠道返回的该发送分组发送成功用户数。
            'email_open_num' => 0,           // 邮件打开的数量 , note : 取该发送分组的独立打开用户数
            'email_open_rate' => 0,             // 邮件打开率 , note : 打开率=[独立打开用户数/发送成功] *100%
            'user_click_num' => 0,           // 用户点击邮件数量（用户点击）, note : 取该发送分组的独立点击用户数
            'user_click_rate' => 0,             // 用户点击邮件率（用户点击率）, note : 点击转化率=[独立点击用户数/独立打开用户数] *100%
            'single_user_num' => 0,     // 下单用户数 (汇总统计该发送分组的下单用户数（按网站用户ID汇总）)
            'single_user_rate' => 0,    // 下单用户率 (用户下单率=[下单用户数/独立点击用户数] *100%)
            'pay_user_num' => 0,        // 付费用户数(用户付款) ,note :汇总统计该发送分组的下过订单并且已支付的用户数（按网站用户ID汇总）
            'pay_user_rate' => 0,       // 付费用户率 note : 用户付款率=[用户付款 /用户下单] *100%
            'bounces_num' => 0,         // 弹回数 note: 弹回总数=硬弹用户数+软弹用户数
            'bounces_rate' => 0,        // 弹回率 note: 弹回率=[弹回总数/发送总量]*100%
            'hard_bounces_num' => 0,    // 硬弹数
            'hard_bounces_rate' => 0,   // 硬弹率 note: 硬弹率=[硬弹用户数/弹回总数]*100%
            'soft_bounces_num' => 0,    // 软弹数
            'soft_bounces_rate' => 0,   // 软弹率 note: 软弹率=[硬弹用户数/弹回总数]*100%
            'complaint_num' => 0,       // 投诉数
            'complaint_rate' => 0,      // 投诉率 note: 投诉率=[投诉用户数/发送成功数] *100%
            'unsubscribe_num' => 0,     // 退订数
            'unsubscribe_rate' => 0,    // 退订率 note: 投诉率=[投诉用户数/发送成功数] *100%
            'mailbox_unsubscribe_num' =>0, // 邮箱退订数
            'mail_unsubscribe_num' => 0,   //邮件退订数
            'mailbox_unsubscribe_rate' => 0, //  邮箱退订率
            'mail_unsubscribe_rate' => 0,    // 邮件退订率
        ];
        $response['terminal'] = [
            "open" =>[
                      'sum' => 0,          // 数量
                      'terminal' =>[
//                                 ['name' => 'other','value' => "0"]
            ]],         
            "complain" => [
                'sum' => 0,          // 数量
                'terminal' =>[
//                   ['name' => 'other','value' => 0]   //value
                   
                ]
            ],
            "single" => [
                'sum' => 0,          // 数量
                'terminal' =>[
//                   ['name' => 'other','value' => 0]
                ]
            ]

        ];
        $response['single'] = ['sku' =>[],'country'=>[],'category'=>[],'single_user'=>[]];
        if (empty($categoryInfo)) {
            return $this->render("/marketing/mail-group/mail-analysis", ['data' => [],'info' => $response,'formData' => $formData,'site' =>$site]);
        }

//        echo "<pre/>";

     //   $categoryInfo = [['group_id' => "16860"],['group_id' => "16856"]];
        foreach ($categoryInfo as $val) {
            $analysisInfo = $collection->find(['group_id'=>$val['group_id']],['_id'=>0,'group_id'=>0]);
            $res = iterator_to_array($analysisInfo);
            //print_r($res[0]['single']);
            if (empty($res)) {
                continue;
            }
            self::dataProcessing($response,$res[0]);
        }
        self::probabilityProcessing($response);
        if (! empty($import_type)) {
            $res = self::exportExcel($response,['name' => $template_name,'type' => $import_type]);
            if (empty($res)) {
                $this->sysMsg('警告', '下载信息为空',
                    [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
            return;
        }

        //概率Probability
//         echo "<pre/>";
//         print_r($response);die;
        return $this->render("/marketing/mail-group/mail-analysis", ['data' => $categoryInfo,'info' => $response,'formData' => $formData,'site' =>$site]);
    }

    /*
     * 获取模板名
     */
    public function actionGetGroupInfo() {
        $method = yii::$app->request->getMethod();
        $template_id = yii::$app->request->$method("template_id");
        $reservation_time = yii::$app->request->$method("reservation_time");
        if (empty($template_id)) {
            $this->sysMsg('警告', '数据不完整，缺少模板template_id',
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $where = '';
        if (! empty($template_id)) {
            $where = "template_id = {$template_id} and is_inside_test = 0 and ";
        }
        if (  ! empty($reservation_time)  ) {
            $timelist = explode(' - ',$reservation_time);
            if (isset($timelist[1]) || !empty($timelist[1]) ) {
                $startTime = Yii::$app->systime->strtotime($timelist[0]);
                $endTime = Yii::$app->systime->strtotime($timelist[1].' +24 hours');
                $where .= " add_date between {$startTime} and {$endTime} and ";
            }
        }
        if ( ! empty($where)) {
            $where = " where ".$where;
            $where = rtrim($where,'and ');
        }

        //查询sql
        $sql = "select group_id,group_name from mail_group {$where}";
        $categoryInfo = yii::$app->db->createCommand($sql)->queryAll();
        $res = [['group_id'=>0,'group_name'=>'全部']];
        if (empty($categoryInfo)) {
            $this->success($res,'没有更多信息');
        }
        $res = array_merge($res,$categoryInfo);
        $this->success($res);
    }


    /**
     *  统计处理
     *  date 2018/7/9
     *  author xianxuefeng
     *  totalTrans = [
     * pay_amount_rate      付款金额率 ,note : 付款金额率=[付款总额/订单总额]*100%
     * pay_order_rate       付款订单率 ,note : 付款订单率=[付款订单数/订单数] *100%
     * email_success_rate   邮件发送成功率 , note :  渠道返回的该发送分组发送成功用户数。
     * email_open_rate      邮件打开率 , note : 打开率=[独立打开用户数/发送成功] *100%
     * user_click_rate      用户点击邮件率（用户点击率）, note : 点击转化率=[独立点击用户数/独立打开用户数] *100%
     * single_user_rate     下单用户率 (用户下单率=[下单用户数/独立点击用户数] *100%)
     * pay_user_rate        付费用户率 note : 用户付款率=[用户付款 /用户下单] *100%
     * bounces_rate         弹回率 note: 弹回率=[弹回总数/发送总量]*100%
     * hard_bounces_rate    硬弹率 note: 硬弹率=[硬弹用户数/弹回总数]*100%
     * soft_bounces_rate    软弹率 note: 软弹率=[硬弹用户数/弹回总数]*100%
     * complaint_rate       投诉率 note: 投诉率=[投诉用户数/发送成功数] *100%
     * unsubscribe_rate     退订率 note: 投诉率=[投诉用户数/发送成功数] *100%
     * mailbox_unsubscribe_rate  邮箱退订率
     * mail_unsubscribe_rate     邮件退订率
     * ]
     *
     * terminal = [
     *
     * ]
     *
     * single = [
     * 'sku' =>[],
     * 'country'=>[],
     * 'category'=>[],
     * 'single_user'=>[]
     * ]
     *
     */
    public function  probabilityProcessing( & $info) {
        $totalTrans = isset($info['totalTrans']) ? $info['totalTrans']: [];
        if ( ! empty($totalTrans)) {

            if ( ! (empty($totalTrans['order_amount']) ||
                empty($totalTrans['pay_order_amount']))) {
                $totalTrans['pay_amount_rate'] = round(100 * $totalTrans['pay_order_amount'] / $totalTrans['order_amount'],2);
            }

            if ( ! (empty($totalTrans['pay_order_num']) ||
                empty($totalTrans['order_num']))) {
                $totalTrans['pay_order_rate'] = round(100 * $totalTrans['pay_order_num'] / $totalTrans['order_num'],2);
            }
            if ( ! (empty($totalTrans['send_email_success_num']) ||
                empty($totalTrans['send_email_num']))) {
                $totalTrans['email_success_rate'] = round(100 *
                    $totalTrans['send_email_success_num'] / $totalTrans['send_email_num'],2);
            }
            if ( ! (empty($totalTrans['email_open_num']) ||
                empty($totalTrans['send_email_success_num']))) {
                $totalTrans['email_open_rate'] = round(100 * $totalTrans['email_open_num'] / $totalTrans['send_email_success_num'],2);
            }

            if ( ! (empty($totalTrans['user_click_num']) ||
                empty($totalTrans['email_open_num']))) {
                $totalTrans['user_click_rate'] = round(100 * $totalTrans['user_click_num'] / $totalTrans['email_open_num'],2);
            }
            if ( ! (empty($totalTrans['single_user_num']) ||
                empty($totalTrans['user_click_num']))) {
                $totalTrans['single_user_rate'] = round(100 * $totalTrans['single_user_num'] / $totalTrans['user_click_num'],2);
            }
            if ( ! (empty($totalTrans['pay_user_num']) ||
                empty($totalTrans['single_user_num']))) {
                $totalTrans['pay_user_rate'] = round(100 * $totalTrans['pay_user_num'] / $totalTrans['single_user_num'],2);
            }

            $totalTrans['bounces_num'] =  $totalTrans['hard_bounces_num']+ $totalTrans['soft_bounces_num'];
            if ( ! (empty($totalTrans['bounces_num']) ||
                empty($totalTrans['send_email_num']))) {
                $totalTrans['bounces_rate'] = round(100 * $totalTrans['bounces_num'] / $totalTrans['send_email_num'],2);
            }

            if ( ! (empty($totalTrans['hard_bounces_num']) ||
                empty($totalTrans['bounces_num']))) {
                $totalTrans['hard_bounces_rate'] = round(100 * $totalTrans['hard_bounces_num'] / $totalTrans['bounces_num'],2);
            }

            if ( ! (empty($totalTrans['soft_bounces_num']) ||
                empty($totalTrans['bounces_num']))) {
                $totalTrans['soft_bounces_rate'] = round (100 * $totalTrans['soft_bounces_num'] / $totalTrans['bounces_num'],2);
            }
            if ( ! (empty($totalTrans['complaint_num']) ||
                empty($totalTrans['send_email_success_num']))) {
                $totalTrans['complaint_rate'] = round (100 * $totalTrans['complaint_num'] / $totalTrans['send_email_success_num'],2);
            }
            if ( ! (empty($totalTrans['unsubscribe_num']) ||
                empty($totalTrans['send_email_success_num']))) {
                $totalTrans['unsubscribe_rate'] =round( 100 * $totalTrans['unsubscribe_num'] / $totalTrans['send_email_success_num'],2);
            }

            if ( ! (empty($totalTrans['mailbox_unsubscribe_num']) ||
                empty($totalTrans['unsubscribe_num']))) {
                $totalTrans['mailbox_unsubscribe_rate'] = round(100 * $totalTrans['mailbox_unsubscribe_num'] / $totalTrans['unsubscribe_num'],2);
            }
            if ( ! (empty($totalTrans['mail_unsubscribe_num']) ||
                empty($totalTrans['unsubscribe_num']))) {
                $totalTrans['mail_unsubscribe_rate'] =round(100 *  $totalTrans['mail_unsubscribe_num'] / $totalTrans['unsubscribe_num'],2);
            }
            $info['totalTrans'] = $totalTrans;
        }

        if ( isset($info['terminal']['open']['terminal']) && ! empty($info['terminal']['open']['terminal'])) {
            $info['terminal']['open']['terminal'] = self::resetIndex($info['terminal']['open']['terminal']);
        }

        if ( isset($info['terminal']['complain']['terminal']) && ! empty($info['terminal']['complain']['terminal'])) {
            $info['terminal']['complain']['terminal'] = self::resetIndex($info['terminal']['complain']['terminal']);
        }

        if ( isset($info['terminal']['single']['terminal']) && ! empty($info['terminal']['single']['terminal'])) {
            $info['terminal']['single']['terminal'] = self::resetIndex($info['terminal']['single']['terminal']);
        }

        if (isset($info['single']['sku']) && ! empty($info['single']['sku'])) {
            foreach ( $info['single']['sku'] as & $val) {
                $val['pay_order_rate'] = 0;
                $val['pay_amount_rate'] = 0;
                if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                    $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
                }
                if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                    $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2);
                }
            }
            $info['single']['sku'] = self::resetIndex($info['single']['sku']);  //重置下标
            unset($val);
        }

        if (isset($info['single']['country']) && ! empty($info['single']['country'])) {
            foreach ( $info['single']['country'] as & $val) {
                $val['pay_order_rate'] = 0;
                $val['pay_amount_rate'] = 0;
                if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                    $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
                }
                if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                    $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2);
                }
            }
            $info['single']['country'] = self::resetIndex($info['single']['country']);  //重置下标
            unset($val);
        }

        if (isset($info['single']['category']) && ! empty($info['single']['category'])) {

            foreach ( $info['single']['category'] as & $val) {
                $val['pay_order_rate'] = 0;
                $val['pay_amount_rate'] = 0;
                if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                    $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
                }
                if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                    $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2);
                }
            }
            $info['single']['category'] = self::resetIndex($info['single']['category']);  //重置下标
            unset($val);
        }


//        if (isset($info['single']['single_user']) && ! empty($info['single']['single_user'])) {
//
//        }

    }



    /**
     *  单封邮件数据处理
     *  date 2018/7/7
     *  author xianxuefeng
     */
     public function dataProcessing(& $info,$data) {
         $totalTrans = $info['totalTrans'];
         $tmpTotal = $data['totalTrans'];
         /*
          * pay_amount_rate      付款金额率 ,note : 付款金额率=[付款总额/订单总额]*100%
          * pay_order_rate       付款订单率 ,note : 付款订单率=[付款订单数/订单数] *100%
          * email_success_rate   邮件发送成功率 , note :  渠道返回的该发送分组发送成功用户数。
          * email_open_rate      邮件打开率 , note : 打开率=[独立打开用户数/发送成功] *100%
          * user_click_rate      用户点击邮件率（用户点击率）, note : 点击转化率=[独立点击用户数/独立打开用户数] *100%
          * single_user_rate     下单用户率 (用户下单率=[下单用户数/独立点击用户数] *100%)
          * pay_user_rate        付费用户率 note : 用户付款率=[用户付款 /用户下单] *100%
          * bounces_rate         弹回率 note: 弹回率=[弹回总数/发送总量]*100%
          * hard_bounces_rate    硬弹率 note: 硬弹率=[硬弹用户数/弹回总数]*100%
          * soft_bounces_rate    软弹率 note: 软弹率=[硬弹用户数/弹回总数]*100%
          * complaint_rate       投诉率 note: 投诉率=[投诉用户数/发送成功数] *100%
          * unsubscribe_rate     退订率 note: 投诉率=[投诉用户数/发送成功数] *100%
          * mailbox_unsubscribe_rate  邮箱退订率
          * mail_unsubscribe_rate     邮件退订率
          */


         $totalTrans['order_amount'] += isset($tmpTotal['order_amount']) ? $tmpTotal['order_amount'] : 0;
         $totalTrans['pay_order_amount'] += isset($tmpTotal['pay_order_amount']) ? $tmpTotal['pay_order_amount'] : 0;
         $totalTrans['order_num'] += isset($tmpTotal['order_num']) ? $tmpTotal['order_num'] : 0;
         $totalTrans['pay_order_num'] += isset($tmpTotal['pay_order_num']) ? $tmpTotal['pay_order_num'] : 0;
         $totalTrans['send_email_num'] += isset($tmpTotal['send_email_num']) ? $tmpTotal['send_email_num'] : 0;
         $totalTrans['send_email_success_num'] += isset($tmpTotal['send_email_success_num']) ? $tmpTotal['send_email_success_num'] : 0;
         $totalTrans['email_open_num'] += isset($tmpTotal['email_open_num']) ? $tmpTotal['email_open_num'] : 0;
         $totalTrans['user_click_num'] += isset($tmpTotal['user_click_num']) ? $tmpTotal['user_click_num'] : 0;
         $totalTrans['single_user_num'] += isset($tmpTotal['single_user_num']) ? $tmpTotal['single_user_num'] : 0;
         $totalTrans['pay_user_num'] += isset($tmpTotal['pay_user_num']) ? $tmpTotal['pay_user_num'] : 0;
         $totalTrans['bounces_num'] += isset($tmpTotal['bounces_num']) ? $tmpTotal['bounces_num'] : 0;
         $totalTrans['hard_bounces_num'] += isset($tmpTotal['hard_bounces_num']) ? $tmpTotal['hard_bounces_num'] : 0;
         $totalTrans['soft_bounces_num'] += isset($tmpTotal['soft_bounces_num']) ? $tmpTotal['soft_bounces_num'] : 0;
         $totalTrans['complaint_num'] += isset($tmpTotal['complaint_num']) ? $tmpTotal['complaint_num'] : 0;
         $totalTrans['unsubscribe_num'] += isset($tmpTotal['unsubscribe_num']) ? $tmpTotal['unsubscribe_num'] : 0;
         $totalTrans['mailbox_unsubscribe_num'] += isset($tmpTotal['mailbox_unsubscribe_num']) ? $tmpTotal['mailbox_unsubscribe_num'] : 0;
         $totalTrans['mail_unsubscribe_num'] += isset($tmpTotal['mail_unsubscribe_num']) ? $tmpTotal['mail_unsubscribe_num'] : 0;


         $terminal = $info['terminal'];
         $tmpTerminal = $data['terminal'];

         foreach($tmpTerminal as $key => $arr ) {
             if( ! isset($terminal[$key])) {
                 $terminal[$key] = [];
             }
             if(! isset($terminal[$key]['sum'])) {
                 $terminal[$key]['sum'] = 0;
             }
             $terminal[$key]['sum'] += $arr['sum'];

             foreach ( $arr['terminal'] as  $item) {
                  $name = $item['name'];
                  if( ! isset($terminal[$key]['terminal'][$name])) {
                      $terminal[$key]['terminal'][$name]['name'] = $item['name'];
                      $terminal[$key]['terminal'][$name]['value'] = 0;
                  }
                 $terminal[$key]['terminal'][$name]['value'] += $item['value'];
             }
         }
         $info['terminal'] = $terminal;;
         $info['totalTrans'] = $totalTrans ;
         self::singleHandle($info,$data);
     }

     private function singleHandle(& $info,$data) {
         $sku = $info['single']['sku'];
         if ( is_array($data['single']['sku'])) {
             foreach ($data['single']['sku'] as $item) {
                 if (!isset($sku[$item['goods_sn']])) {
                     $sku[$item['goods_sn']]['goods_sn'] = isset($item['goods_sn']) ? $item['goods_sn'] : "不确定" ;
                     $sku[$item['goods_sn']]['order_goods_num'] = isset($item['order_goods_num']) ? $item['order_goods_num'] : 0 ;
                     $sku[$item['goods_sn']]['order_num'] = isset($item['order_num']) ? $item['order_num'] : 0 ;
                     $sku[$item['goods_sn']]['order_amount'] = isset($item['order_amount']) ? $item['order_amount'] : 0 ;
                     $sku[$item['goods_sn']]['goods_name'] = isset($item['goods_name']) ? $item['goods_name'] : 0 ;
                     $sku[$item['goods_sn']]['category_id'] = isset($item['category_id']) ? $item['category_id'] : 0;
                     $sku[$item['goods_sn']]['category_name'] = isset($item['category_name']) ? $item['category_name'] : '' ;
                     $sku[$item['goods_sn']]['pay_order_num'] = isset($item['pay_order_num']) ? $item['pay_order_num'] : 0 ;
                     $sku[$item['goods_sn']]['pay_order_amount'] = isset($item['pay_order_amount']) ? $item['pay_order_amount'] : 0 ;
                     $sku[$item['goods_sn']]['single_user_num'] = isset($item['single_user_num']) ? $item['single_user_num'] : 0 ;
                     $sku[$item['goods_sn']]['pay_single_user_num'] = isset($item['pay_single_user_num']) ? $item['pay_single_user_num'] : 0 ;

                 } else {
                     $sku[$item['goods_sn']]['order_goods_num'] += isset($item['order_goods_num']) ? $item['order_goods_num'] : 0 ;
                     $sku[$item['goods_sn']]['order_num'] += isset($item['order_num']) ? $item['order_num'] : 0 ;
                     $sku[$item['goods_sn']]['order_amount'] += isset($item['order_amount']) ? $item['order_amount'] : 0 ;
                     $sku[$item['goods_sn']]['pay_order_num'] += isset($item['pay_order_num']) ? $item['pay_order_num'] : 0 ;
                     $sku[$item['goods_sn']]['pay_order_amount'] += isset($item['pay_order_amount']) ? $item['pay_order_amount'] : 0 ;
                     $sku[$item['goods_sn']]['single_user_num'] += isset($item['single_user_num']) ? $item['single_user_num'] : 0 ;
                     $sku[$item['goods_sn']]['pay_single_user_num'] += isset($item['pay_single_user_num']) ? $item['pay_single_user_num'] : 0 ;
                 }
             }
         }

         $country = $info['single']['country'];
         
         if (is_array($data['single']['country'])) {
             foreach ($data['single']['country'] as $item) {
                 if (!isset($country[$item['country']])) {
                     $country[$item['country']]['country'] = isset($item['country']) ? $item['country'] : '' ;
                     $country[$item['country']]['order_goods_num'] = isset($item['order_goods_num']) ? $item['order_goods_num'] : 0 ;
                     $country[$item['country']]['order_num'] = isset($item['order_num']) ? $item['order_num'] : 0 ;
                     $country[$item['country']]['order_amount'] = isset($item['order_amount']) ? $item['order_amount'] : 0 ;
                     $country[$item['country']]['pay_order_num'] = isset($item['pay_order_num']) ? $item['pay_order_num'] : 0 ;
                     $country[$item['country']]['pay_order_amount'] = isset($item['pay_order_amount']) ? $item['pay_order_amount'] : 0 ;
                     $country[$item['country']]['single_user_num'] = isset($item['single_user_num']) ? $item['single_user_num'] : 0 ;
                     $country[$item['country']]['pay_single_user_num'] = isset($item['pay_single_user_num']) ? $item['pay_single_user_num'] : 0 ;
                 } else {
                     $country[$item['country']]['order_goods_num'] += isset($item['order_goods_num']) ? $item['order_goods_num'] : 0 ;
                     $country[$item['country']]['order_num'] += isset($item['order_num']) ? $item['order_num'] : 0 ;
                     $country[$item['country']]['order_amount'] += isset($item['order_amount']) ? $item['order_amount'] : 0 ;
                     $country[$item['country']]['pay_order_num'] += isset($item['pay_order_num']) ? $item['pay_order_num'] : 0 ;
                     $country[$item['country']]['pay_order_amount'] += isset($item['pay_order_amount']) ? $item['pay_order_amount'] : 0 ;
                     $country[$item['country']]['single_user_num'] += isset($item['single_user_num']) ? $item['single_user_num'] : 0 ;
                     $country[$item['country']]['pay_single_user_num'] += isset($item['pay_single_user_num']) ? $item['pay_single_user_num'] : 0 ;
                 }
             }
         }

         $category = $info['single']['category'];

         if (is_array($data['single']['category'])) {
             foreach ( $data['single']['category'] as $item) {
                 if (!isset($category[$item['category_id']])) {
                     $category[$item['category_id']]['category_name'] = isset($item['category_name']) ? $item['category_name'] : '' ;
                     $category[$item['category_id']]['category_id'] = isset($item['category_id']) ? $item['category_id'] : 0 ;
                     $category[$item['category_id']]['order_goods_num'] = isset($item['order_goods_num']) ? $item['order_goods_num'] : 0 ;
                     $category[$item['category_id']]['order_num'] = isset($item['order_num']) ? $item['order_num'] : 0 ;
                     $category[$item['category_id']]['order_amount'] = isset($item['order_amount']) ? $item['order_amount'] : 0 ;
                     $category[$item['category_id']]['pay_order_num'] = isset($item['pay_order_num']) ? $item['pay_order_num'] : 0 ;
                     $category[$item['category_id']]['pay_order_amount'] = isset($item['pay_order_amount']) ? $item['pay_order_amount'] : 0 ;
                     $category[$item['category_id']]['single_user_num'] = isset($item['single_user_num']) ? $item['single_user_num'] : 0 ;
                     $category[$item['category_id']]['pay_single_user_num'] = isset($item['pay_single_user_num']) ? $item['pay_single_user_num'] : 0 ;
                 } else {
                     $category[$item['category_id']]['order_goods_num'] += isset($item['order_goods_num']) ? $item['order_goods_num'] : 0 ;
                     $category[$item['category_id']]['order_num'] += isset($item['order_num']) ? $item['order_num'] : 0 ;
                     $category[$item['category_id']]['order_amount'] += isset($item['order_amount']) ? $item['order_amount'] : 0 ;
                     $category[$item['category_id']]['pay_order_num'] += isset($item['pay_order_num']) ? $item['pay_order_num'] : 0 ;
                     $category[$item['category_id']]['pay_order_amount'] += isset($item['pay_order_amount']) ? $item['pay_order_amount'] : 0 ;
                     $category[$item['category_id']]['single_user_num'] += isset($item['single_user_num']) ? $item['single_user_num'] : 0 ;
                     $category[$item['category_id']]['pay_single_user_num'] += isset($item['pay_single_user_num']) ? $item['pay_single_user_num'] : 0 ;
                 }
             }
         }
         $single_user = $info['single']['single_user'];
         if (is_array($data['single']['single_user'])) {
             foreach($data['single']['single_user'] as $key => $item) {
                 if(! isset($single_user[$key])) {
                     $single_user[$key] = 0;
                 }
                 $single_user[$key] += $item;
             }
         }
         $info['single']['sku'] =  $sku ;
         $info['single']['country'] =  $country;
         $info['single']['category'] = $category;
         $info['single']['single_user'] = $single_user;
     }

     /*
      *  邮件打开和点击分析
      *  params :
      *  template_id
      *  reservation_time
      *  email_type
      *  is_click
      *  author xianxuefeng
      *  date 2018/7/9
      */

     public  function actionEmailOpenAndClickAnalysis() {
         $method = yii::$app->request->getMethod();
         $template_id = yii::$app->request->$method("template_id");
         $reservation_time = yii::$app->request->$method("reservation_time");
         $post = $_REQUEST;
         if (empty($template_id)) {
             $this->sysMsg('警告', '数据不完整，缺少模板template_id',
                 [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
         }
         $where = "template_id = {$template_id} and is_inside_test = 0 and ";
//         if ( ! empty($template_id)) {
//             $where = "template_id = {$template_id} and is_inside_test = 0 and ";
//         }
         if (empty($reservation_time)) {
             $this->sysMsg('警告', '数据不完整，缺少模板reservation_time',
                 [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
         }
         if (  ! empty($reservation_time)  ) {
             $timelist = explode(' - ',$reservation_time);
             $start_time = Yii::$app->systime->strtotime($timelist[0]);
             $end_time = Yii::$app->systime->strtotime($timelist[1].' +24 hours');
//             $start_time = strtotime($timelist[0]);
//             $end_time = strtotime($timelist[1]) + 24*60*60;
             $where .= " add_date between {$start_time} and {$end_time} ";
         }
         if ( ! empty($where)) {
             $where = " where ".$where;
             $where = rtrim($where,"and ");
         }
         //查询sql
         $sql = "select group_id,group_name from mail_group {$where}";
         $categoryInfo = yii::$app->db->createCommand($sql)->queryAll();

         if (empty($categoryInfo)) {
             return $this->render("/marketing/mail-group/mail-analysis", ['data' => [],'info' => []]);
         }

         if(isset($post['email_type']) && ! empty($post['email_type'])) {
             $cond['email_type'] = $post['email_type'];
         }
         if(isset($post['is_click']) && is_numeric($post['is_click'])) {
             $cond['is_click'] = (string)$post['is_click'];
         }
       //  echo "<pre/>";
         $terminal = [];
         foreach ($categoryInfo as $val) {
             $cond['group_id'] = $val['group_id'];
//             $resInfo = self::openAndclick(['group_id'=>15571,'email_type' =>'5','is_click'=>'1']);
             $resInfo = self::openAndclick($cond);
             if (empty($resInfo)) {
                 continue;
             }
             foreach($resInfo as $key => $arr ) {
                 if( ! isset($terminal[$key])) {
                     $terminal[$key] = [];
                 }
                 if(! isset($terminal[$key]['sum'])) {
                     $terminal[$key]['sum'] = 0;
                 }
                 $terminal[$key]['sum'] += $arr['sum'];
                 foreach ( $arr['terminal'] as  $item) {
                     $name = $item['name'];
                     if( ! isset($terminal[$key]['terminal'][$name])) {
                         $terminal[$key]['terminal'][$name]['name'] = $item['name'];
                         $terminal[$key]['terminal'][$name]['value'] = 0;
                     }
                     $terminal[$key]['terminal'][$name]['value'] += $item['value'];
                 }
             }
         }

         if ( isset($terminal['open']['terminal']) && ! empty($terminal['open']['terminal'])) {
             $terminal['open']['terminal'] = self::resetIndex($terminal['open']['terminal']);
         }
        

         if ( isset($terminal['complain']['terminal']) && ! empty($terminal['complain']['terminal'])) {
             $terminal['complain']['terminal'] = self::resetIndex($terminal['complain']['terminal']);
         }
         if (empty($terminal)) {
             $this->error();
         }
         $this->success($terminal);
     }



    /*
     *  邮件打开和点击分析
     *  params :
     *  template_id
     *  pay_status
     *  reservation_time
     *  author xianxuefeng
     *  date 2018/7/9
     *
     */

    public  function actionEmailOrderDivision() {
        $method = yii::$app->request->getMethod();
        $template_id = yii::$app->request->$method("template_id");
        $reservation_time = yii::$app->request->$method("reservation_time");
        $pay_status = yii::$app->request->$method("pay_status");
        if (empty($template_id)) {
            $this->sysMsg('警告', '数据不完整，缺少模板template_id',
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        if (empty($reservation_time)) {
            $this->sysMsg('警告', '数据不完整，缺少模板reservation_time',
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $where = "template_id = {$template_id} and is_inside_test = 0 and ";
//        if (! empty($template_id)) {
//            $where = "template_id = {$template_id} and is_inside_test = 0 and ";
//        }
        if (  ! empty($reservation_time)  ) {
            $timelist = explode(' - ',$reservation_time);
//            $start_time = strtotime($timelist[0]);
//            $end_time = strtotime($timelist[1]) + 24*60*60-1;
            $start_time = Yii::$app->systime->strtotime($timelist[0]);
            $end_time = Yii::$app->systime->strtotime($timelist[1].' +24 hours');
            $where .= " add_date between {$start_time} and {$end_time} ";
        }

        if ( ! empty($where)) {
            $where = " where ".$where;
            $where = rtrim($where,"and ");
        }

        //查询sql
        $sql = "select group_id,group_name from mail_group {$where}";
        $categoryInfo = yii::$app->db->createCommand($sql)->queryAll();

        if (empty($categoryInfo)) {
            return $this->render("/marketing/mail-group/mail-analysis", ['data' => [],'info' => []]);
        }

        if(isset($pay_status) &&  is_numeric($pay_status)) {
            $cond['pay_status'] = $pay_status;
        }

       //   echo "<pre/>";
        $terminal = [];
        foreach ($categoryInfo as $val) {
            $cond['group_id'] = $val['group_id'];
//             $resInfo = self::openAndclick(['group_id'=>15571,'email_type' =>'5','is_click'=>'1']);
            $resInfo = self::orderDivision($cond);
//            var_dump($resInfo);die;
            if (empty($resInfo)) {
                continue;
            }

                if(! isset($terminal['sum'])) {
                    $terminal['sum'] = 0;
                }
                $terminal['sum'] += $resInfo['sum'];
                foreach ( $resInfo['terminal'] as  $item) {
                    $name = $item['name'];
                    if( ! isset($terminal['terminal'][$name])) {
                        $terminal['terminal'][$name]['name'] = $item['name'];
                        $terminal['terminal'][$name]['value'] = 0;
                    }
                    $terminal['terminal'][$name]['value'] += $item['value'];
                }

        }
        // echo "<pre/>";
        // print_r($terminal);die;

        if ( isset($terminal['terminal']) && ! empty($terminal['terminal'])) {
            $terminal['terminal'] = self::resetIndex($terminal['terminal']);
        }
//        print_r($terminal);die;
        if (empty($terminal)) {
            $this->error();
        }
        $this->success($terminal);
    }

    /**
     * @param $info
     * @param $data ['type' =>'sku','name' => 'test']
     * @return bool
     * 邮件下单execel 导出
     */

    private function exportExcel($info,$data) {
        if (! isset($data['type'],$data['name']) || empty($info) || empty($data['type']) || empty($data['name'])) {
            return false;
        }
        date_default_timezone_set('Asia/Shanghai');
        switch ($data['type']) {
            case "sku" :
                $time = date('Y-m-d',time());
                $file = $data['name'].'_SKU_'."{$time}".'.csv';
                $return = self::skuExportExcel($info,$file);
                return $return;
            case 'category' :
                $time = date('Y-m-d',time());
                $file = $data['name'].'_category_'."{$time}".'.csv';
                $return =self::categoryExportExcel($info,$file);
                return $return;
            case 'country':
//                $time = date('Y-m-d h-i-s',time());
                $time = date('Y-m-d',time());
                $file = $data['name'].'_country_'."{$time}".'.csv';
                $return =self::countryExportExcel($info,$file);
                return $return;
            default:
                break;
        }
        return true;
    }


    private function skuExportExcel($info,$downloadFilename = '') {

        if (! isset($info['single']['sku']) || empty($info['single']['sku'])) {
            return false;
        }
        date_default_timezone_set('Asia/Shanghai');
        if (empty($downloadFilename)) {
            $time = date('Y-m-');
            $downloadFilename = 'SKU_'."{$time}".'.csv';
        }

        $info = $info['single']['sku'];
        // 下载文件输出头
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="'. $downloadFilename .'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        $fp = fopen('php://output', 'a');//打开output流
        $title = ['SKU','商品名称','所属分类','商品数量','下单用户','付费用户','订单数','付款订单数','付费订单率','订单金额','付款金额','付款金额率'];

        fputcsv($fp, $title);//将数据名称格式化为CSV格式并写入到output流中
        foreach ($info as $val) {
            $exportData = [];
            $exportData[] = isset($val['goods_sn']) ? $val['goods_sn'] : "";
            $exportData[] = isset($val['goods_name']) ? $val['goods_name'] : "";
            $exportData[] = isset($val['category_name']) ? $val['category_name'] : "";
            $exportData[] = isset($val['order_goods_num']) ? $val['order_goods_num'] : "0";
            $exportData[] = isset($val['single_user_num']) ? $val['single_user_num'] : "0";
            $exportData[] = isset($val['pay_single_user_num']) ? $val['pay_single_user_num'] : "0";
            $exportData[] = isset($val['order_num']) ? $val['order_num'] : "0";
            $exportData[] = isset($val['pay_order_num']) ? $val['pay_order_num'] : "0";
            $exportData[] = isset($val['pay_order_rate']) ? $val['pay_order_rate']  .'%': "0%";
            $exportData[] = isset($val['order_amount']) ? $val['order_amount'] : "0";
            $exportData[] = isset($val['pay_order_amount']) ? $val['pay_order_amount'] : "0" ;
            $exportData[] = isset($val['pay_amount_rate']) ? $val['pay_amount_rate'].'%' : "0%";
            fputcsv($fp, $exportData);//将数据格式化为CSV格式并写入到output流中
        }
//        fputcsv($fp, $title);//将数据名称格式化为CSV格式并写入到output流中
//        fputcsv($fp, []);//将数据格式化为CSV格式并写入到output流中
        //刷新输出缓冲到浏览器
        ob_flush();
        flush();//必须同时使用 ob_flush() 和flush() 函数来刷新输出缓冲。
        fclose($fp);
        return true;
    }

    private function categoryExportExcel($info,$downloadFilename = '') {

        if (! isset($info['single']['category']) || empty($info['single']['category'])) {
            return false;
        }
        if (empty($downloadFilename)) {
            $time = date('Y-m-d h-i-s');
            $downloadFilename = 'category_'."{$time}".'.csv';
        }
        $info = $info['single']['category'];
        // 下载文件输出头
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="'. $downloadFilename .'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        $fp = fopen('php://output', 'a');//打开output流
        $title = ['商品品类','商品数量','下单用户','付费用户','订单数','付款订单数','付费订单率','订单金额','付款金额','付款金额率'];

        fputcsv($fp, $title);//将数据名称格式化为CSV格式并写入到output流中
        foreach ($info as $val) {
            $exportData = [];
            $exportData[] = isset($val['category_name']) ? $val['category_name'] : "";
            $exportData[] = isset($val['order_goods_num']) ? $val['order_goods_num'] : "0";
            $exportData[] = isset($val['single_user_num']) ? $val['single_user_num'] : "0";
            $exportData[] = isset($val['pay_single_user_num']) ? $val['pay_single_user_num'] : "0";
            $exportData[] = isset($val['order_num']) ? $val['order_num'] : "0";
            $exportData[] = isset($val['pay_order_num']) ? $val['pay_order_num'] : "0";
            $exportData[] = isset($val['pay_order_rate']) ? $val['pay_order_rate']  .'%': "0%";
            $exportData[] = isset($val['order_amount']) ? $val['order_amount'] : "0";
            $exportData[] = isset($val['pay_order_amount']) ? $val['pay_order_amount'] : "0" ;
            $exportData[] = isset($val['pay_amount_rate']) ? $val['pay_amount_rate'].'%' : "0%";
            fputcsv($fp, $exportData);//将数据格式化为CSV格式并写入到output流中
        }
//        fputcsv($fp, $title);//将数据名称格式化为CSV格式并写入到output流中
//        fputcsv($fp, []);//将数据格式化为CSV格式并写入到output流中
        //刷新输出缓冲到浏览器
        ob_flush();
        flush();//必须同时使用 ob_flush() 和flush() 函数来刷新输出缓冲。
        fclose($fp);
        return true;
    }

    private function countryExportExcel($info,$downloadFilename = '') {
        if (! isset($info['single']['country']) || empty($info['single']['country'])) {
            return false;
        }
        if (empty($downloadFilename)) {
            $time = date('Y-m-d h-i-s');
            $downloadFilename = 'country_'."{$time}".'.csv';
        }

        $info = $info['single']['country'];
        // 下载文件输出头
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="'. $downloadFilename .'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        $fp = fopen('php://output', 'a');//打开output流
        $title = ['国家','下单用户','付费用户','订单数','付款订单数','付款订单率','订单金额','付款金额','付款金率'];

        fputcsv($fp, $title);//将数据名称格式化为CSV格式并写入到output流中
        foreach ($info as $val) {
            $exportData = [];
            $exportData[] = isset($val['country']) ? $val['country'] : "";
            $exportData[] = isset($val['single_user_num']) ? $val['single_user_num'] : "0";
            $exportData[] = isset($val['pay_single_user_num']) ? $val['pay_single_user_num'] : "0";
            $exportData[] = isset($val['order_num']) ? $val['order_num'] : "0";
            $exportData[] = isset($val['pay_order_num']) ? $val['pay_order_num'] : "0";
            $exportData[] = isset($val['pay_order_rate']) ? $val['pay_order_rate']  .'%': "0%";
            $exportData[] = isset($val['order_amount']) ? $val['order_amount'] : "0";
            $exportData[] = isset($val['pay_order_amount']) ? $val['pay_order_amount'] : "0" ;
            $exportData[] = isset($val['pay_amount_rate']) ? $val['pay_amount_rate'].'%' : "0%";
            fputcsv($fp, $exportData);//将数据格式化为CSV格式并写入到output流中
        }
//        fputcsv($fp, $title);//将数据名称格式化为CSV格式并写入到output流中
//        fputcsv($fp, []);//将数据格式化为CSV格式并写入到output流中
        //刷新输出缓冲到浏览器
        ob_flush();
        flush();//必须同时使用 ob_flush() 和flush() 函数来刷新输出缓冲。
        fclose($fp);
        return true;
    }

}